我试图让球在 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 是在 animate 中本地声明和初始化的。这意味着,每次调用 animate 时,它都会被重新初始化。
只需将 vX 和 vY 声明移出 animate 函数即可。
编辑:如果您想查看 JsFiddle 的实际效果:http://jsfiddle.net/y45fhko7/
关于javascript - Canvas 中的弹跳球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852392/