Need better way of making the ball angle in pong game

ぐ巨炮叔叔 提交于 2019-12-12 02:43:35

问题


I'm making a pong clone to practice my coding, and I've become stuck on making the ball be able to change angle when hit by the paddle.

My current implementation has a deltaX and deltaY for the ball, which moves with the game loop to move the ball. The way I have done it is that if you hit the ball while the paddle is moving, the deltaY is increased or decreased depending on the direction of the paddle, but this does not feel natural at all for the game.

Does anyone know a better way of doing this?


回答1:


First thing I would do is change the deltaX and deltaY to ballAngle and deltaSpeed. That way you'd be moving from a rectangular coordinates system to a polar one. Due to the nature of the movement of the ball (Goes in a straight line and changes the angle of the line at each impact) this will make your work easier. From now on you'd only have to change ballAngle to update the ball's direction.

However you'll have to update the function that draws the balls for it to move back from polar to rectangular coordinates so you can display it on the screen. A little bit of high-school trigonometry will let you calculate screen position deltas depending on your angle and speed:

newPosition = oldPosition + movementVector

with:

movementVector.x = deltaSpeed*cos(ballAngle)
movementVector.y = deltaSpeed*sin(ballAngle)

Of course these equations might need some modification based on relative to what you measure the ball's angle.

Now to modify the ball's angle at each collision with the paddle, you only have to increment or decrement the angle of the ball depending on which part of the paddle it touches, and the math in the drawing function should take care of updating x and y positions realistically.

I hope this helps.



来源:https://stackoverflow.com/questions/11720293/need-better-way-of-making-the-ball-angle-in-pong-game

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!