My student would like one of his sprites to chase another sprite. How would he do this?
I would like some help with this as well.
Does he want it to follow the other sprite’s trail or to always move in the direction the target sprite currently is?
Move in the direction that the target Sprite currently is. The idea is that the good guy is one Sprite and the bad guy is another Sprite and the bad guy should be trying to catch the good guy.
Here’s the simplest version of “chasing”, in which the ship chases the mouse cursor around the screen. The general idea is that you can get the angle right by finding the difference between the mouse cursor and the ship in both the x and y directions. As long as your x and y velocities maintain this same ratio, the ship will move in the correct direction. I used a 10:1 ratio (divided the difference in position by ten for the velocity) to ensure that the ship didn’t catch the cursor too quickly.
In this second version, I used trig to make the velocity constant. Notice that when deltaX is negative, the angle ends up in the second or third quadrant, so you’re going to get the wrong angle value. You have to correct by adding pi to the angle.
In this one, I control the green ship with the arrow keys, and the orange ship chases me.
Here, I pulled out the chasing into a function and added some colliders. That way the green ship can’t go off the screen, and it makes a sound when the orange ship catches up.