Can you make a sprite chase another sprite?


#1

My student would like one of his sprites to chase another sprite. How would he do this?


#5

I would like some help with this as well.


#6

Does he want it to follow the other sprite’s trail or to always move in the direction the target sprite currently is?

Elizabeth


#7

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.


#8

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.

chase mouse

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.

chase mouse constant velocity

In this one, I control the green ship with the arrow keys, and the orange ship chases me.

ship chase ship

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.

final chaser game