Here is my code:
if (ball.position.y < 0 || ball.position.y > size.height) {
ball_speed.y *= -1;
}
开发者_Python百科 if (ball.position.x < 0 || ball.position.x > size.width) {
ball_speed.x *= -1;
}
I am making my game in cocos2d, ball is a sprite and ball_speed is a CGPoint. What happens sometimes the ball freezes at the edge of the screen and just vibrates. Could anyone help me on this it would be appreciated.
You're applying the logic "if the ball is outside the screen, reverse its velocity along the corresponding axis", which is incorrect: maybe the ball is outside the screen but already moving the right way. This happens a lot of your velocity is altered by things other than bounces (such as gravity or friction).
The first part of the solution is to set the direction explicitly:
if (ball.position.y < 0)
ball_speed.y = fabs(ball_speed.y);
if (ball.position.y > size.height)
ball_speed.y = - fabs(ball_speed.y);
This will ensure that the ball will indeed move back into the screen, so there is no possibility of oscillating at the edge.
The second part, which is optional but nonetheless useful if you want correct physics, is to move back the ball into the screen whenever it leaves:
if (ball.position.y < 0)
ball.position.y = 2 * 0 - ball.position.y ;
if (ball.position.y > size.height)
ball.position.y = 2 * size.height - ball.position.y;
Notice the pos = 2 * limit - pos
which basically mirrors pos
around limit
.
精彩评论