Search code examples
performancealgorithmlinepong

Updating position of an object with constant speed, regardless of direction


I think this question is a little but stupid but I can't find the answer.

I'm doing the classic game pong. And I want that the ball goes at the same speed for any angle. But with my current algorithm (incrementing x by one and calculating y) if the a in y=ax+b is high there is big gaps between each pixel. What step should I use?


Solution

  • So we have something like this:

      newPoint
      |\
      | \
    y |  \ r
      |  θ\
      |-----
         x  oldPoint
    

    What you basically want is to make a step in distance related to r, not x.

    From elementary trig:
    cos θ = x/r
    and sin θ = y/r

    So newX = oldX + r * cos θ
    and newY = oldY + r * sin θ

    You can play around with r's value (this will basically be the speed of movement).

    θ will be the direction of the ball.