Javascript 如何使对象从画布边缘反弹
我正在尝试制作一个HTML/JavaScript游戏,但我需要让我的一个对象从画布边缘反弹,而不是跑掉 这是我的密码:Javascript 如何使对象从画布边缘反弹,javascript,html,css,html5-canvas,Javascript,Html,Css,Html5 Canvas,我正在尝试制作一个HTML/JavaScript游戏,但我需要让我的一个对象从画布边缘反弹,而不是跑掉 这是我的密码: 你的想法是对的。您的对象具有一个x&y位置,该位置在每一帧中以相应的x或y速度递增/递减。现在,您需要做的就是检测对象何时与画布的边界发生碰撞,并抵消相应方向上的速度,以将对象发送到相反的轨迹 下面是一些伪代码: // Called each frame to update the position of the object. updatePosition(): hand
你的想法是对的。您的对象具有一个x&y位置,该位置在每一帧中以相应的x或y速度递增/递减。现在,您需要做的就是检测对象何时与画布的边界发生碰撞,并抵消相应方向上的速度,以将对象发送到相反的轨迹 下面是一些伪代码:
// Called each frame to update the position of the object.
updatePosition():
handleCollision()
updatePosition()
// Detects a collision with a wall, calculating the bounce offset, and new velocity if applicable.
handleCollision():
// Detect collision with right wall.
if (object.x + object.width > canvas.width)
// Need to know how much we overshot the canvas width so we know how far to 'bounce'.
overshootX = (object.x + object.width) - canvas.width
object.x = canvas.width - overshootX - object.width
velocityX = -velocityX
// Repeat the same algorithm for top, left, and bottom walls.
我试着做这样的事,但没有用。以下是(this.x+this.y>canvas.width){overshootX=(this.x+this.y)-canvas.width this.x=canvas.width-overshootX-this.y this.angle=-this.angle}的代码