Search code examples
javapathcurve

Java - Round Player Turning


I am making a game, and I got the player to move, but when the player turns at a diagonal (Up, then up-right, for example), it's not as smooth as I want it to be. Here's a picture showing the issue: enter image description here

The player lines indicate the player's path. How can I achieve this effect?

I'm thinking of maybe generating a bezier curve for the player to follow, but I don't know how I would get the player to follow it.


Solution

  • You are correct in your assumption of using a bezier curve. I would suggest (if you don't have it already) writing an Update method which you use to control the player movement on a frame-by-frame basis. In other words; a method which runs in a separate thread and triggers position updates for the player you want to move along the curve. It would act as a queue, only executing movements etc when a given amount of time has elapsed.

    As for how to get the player to move along the curve, I would calculate multiple points along the curve, let's say 25 per curve. Have each point, point to the next point. These will act like waypoints - the player is given the instruction to move to the next waypoint over a short amount of time. So if you wanted to move your player along the whole curve within 5 seconds, the player would need to 'jump' from one waypoint to another every 0.2 seconds.

    If you wanted the movement to be less 'jerking', you would need to write linear interpolation which would in effect further calculate smaller divisions of waypoints between each of the curve waypoints.

    You can find many helpful methods for the items described above, here

    In the image below, the blue blobs are waypoints. Visual Description of points made above


    Alternative (Simpler) Curve Approach

    An alternative approach to using a bezier curve is to do a very simple smooth curve: In the case of turning right; start off with two values- Xfactor = 0, and Yfactor = 10. For this example, I assume that the speed of movement around the curve is 10 units (it could be pixels for example). For each frame, you add Xfactor and Yfactor to the players current position. You also subtract a constant (let's say 0.5 units) from the Yfactor and add it to the Xfactor. You keep going until the Xfactor equals 10 and Yfactor equals 0. This should cause the player to 'move' through 90 degrees. In order to get the player to move through 45 degrees, you would keep going until the Xfactor equals 5, as this would be half of 10. To keep the player moving in that direction, you would need to keep adding the Xfactor and Yfactor to the player position on each frame/update. Again, to make the player turn, you change the Xfactor and Yfactor over time.