We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello there, I am creating an air hockey style game, and I am having an issue with the 'puck' bouncing off the sides. I have the code below(and the corresponding one for Y direction).
pX += pSpX*pDirX;
if (pX > width-pRad/2 || pX < 0+pRads/2)
{
pDirX = -pDirX;
pSpX = 0.8*pSpX;
if(pSpX < 0.4)
{
pSpX = 0.4;
}
}
The intention is that when the puck hits the side, the direction will reverse, and the 'speed' will decrease by a chunk each time it hits a side. When I first did this, I noticed that as it slowed down it would sometimes just glitch and move only along an axis. I tried to add a 'minimum' function(speed never less than 0.4) which seems to have decreased the occurrence of this, but it still happens and with no apparent pattern to me. Would anyone be able to advise as to why this happens , and how I could fix it?
Answers
Your puck is getting stuck. It's trying to bounce back, but it's not going fast enough to get away from the wall on the next frame. The fix is to set the puck's position to the boundry value when it bounces:
Thank you very much, you are spot on!