I am making a defence game. Naturally, this means that there needs to be objects following a path on the screen. I want to make it a strict path from one point to another to another. I could use an array of vertices, but i need some help. Can someone please show me some code that could help me with this? Thanks.
Okay, I gave it a quick test run and it seems to be working on my end. Here's my solution. Imagine your entity has the following members, and you'd like to make the entity follow whatever path is currently set to the
I started by adding an helper method inside the class that moves the entity towards some goal, and returns true if that goal was reached:
Using this helper method, following the path is as simple as doing:
I think the only line that isn't really clear is the following:
What I'm doing here is checking if the direction before the move, and the direction after the move are opposite. I do this by checking if the dot product between both directions is close to -1 using an epsilon comparison. Another solution that seems to work is replacing the same check by:
When I tried it the result was the same. As for the update loop:
It's relying on the && operator not bothering to run the second portion of the operation unless the first one is true. So if there's no path, nothing else happens. If there's a path, then