javaperformancegame-physicspath-2d

Let an Enemy follow a path with the same speed


I started programming a game in java. I have Enemys and a Player, a basic 2D game, thats to get experience for the first time.

Now i wanted the Enemys to follow a path, which i can draw in to a "level editor". I have a JPanel, a mouseMoveListener, and on click the Path2D starts saving the mouseMove Points to a Path2D.Double Object.

After that, i implemented the following method to make the enemys following this path:

public void forward(){
    if(!pathIterator.isDone()){
        pathIterator.currentSegment(current);
        x = current[0];
        y = current[1];
        pathIterator.next();
    }
    else {
        dead = true;
    }
}

I think its clear what happens now: The Enemy is following, but the speed is that i moved the mouse with. So if i move to Mouse to fast, the enemy just.. "jumps" from one point to an other. To slow, its "sneaking" over that points. (And because im not an Robot, i cannot move the Mouse with the same speed ^^)

Talking of Robot: Yes, i could let a awt.Robot move my Mouse. But this isnt really possible too, because i have to draw complicated paths, which dont have any visible mathematics behind.

So, i want let this Enemys to move on this path with the same speed. My Problem: I don't know where to implement a "fix". I have 2 Ideas:

So, are that ways possible, and if yes, has someone an idea how to calculate this? And, if not, what other possibilitys i have to achieve this?

Thank you, and sorry for the bad english!


Solution

  • All you need to do is define the speed of movement of the enemy inside the enemy class.

    When it works out the next point to move to then create a direction vector by subtracting the current position from the new position.

    Normalize the direction vector (so it is length 1) then multiply it by the speed and the tpf (time per frame).

    Move by that amount instead of jumping to the next point.

    (Note if the points are very close together or the framerate is low this can cause it to overshoot a bit, it should be fine though).