[英]Bouncing ball in Canvas
我正在嘗試使球在畫布內彈跳,但不起作用。 球被卡在“牆壁”上,我不明白為什么。 有人知道我該如何解決嗎?
var can = document.querySelector("canvas");
var ctx = can.getContext("2d");
var canvasWidth = 500;
var canvasHeight = 400;
var radius = 30;
var pX = 60;
var pY = 50;
function draw() {
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(pX, pY, radius, 0, Math.PI * 2, false);
ctx.fill();
ctx.closePath();
}
function animate() {
var vX = 3;
var vY = 3;
if (pY >= canvasHeight - radius) {
vY = -vY;
}
if (pX >= canvasWidth - radius) {
vX = -vX;
}
pX += vX;
pY += vY;
draw();
requestAnimationFrame(animate);
}
animate();
您的碰撞檢測條件僅考慮底壁和右側壁。 您需要為頂牆和左側牆添加條件。 就像是
if (pY >= canvasHeight - radius || pY <= radius) {
vY = -vY;
}
if (pX >= canvasWidth - radius || pX <= radius) {
vX = -vX;
}
由於vX和vY在本地聲明並以動畫形式初始化,因此您會在碰撞檢測中看到奇怪的行為。 這意味着,每次調用動畫時,它將被重新初始化。
只需將vX和vY聲明移出動畫函數即可。
編輯:JsFiddle如果您想在實際中看到它: http : //jsfiddle.net/y45fhko7/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.