У вас есть правильная идея. Ваш объект имеет положение 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.
Я пытался сделать что-то вроде этого, но он не работает. Вот код if (this.x + this.y> canvas.width) { overshootX = (this.x + this.y) - canvas.width это.x = canvas.width - overshootX - this.y this.angle = -this.angle } –