How to make sprite follow other sprite.

Looking for a way to have a sprite follow another sprite. I have some somewhat unique code that detects collision and position in a public method for the class.

   public Player(Vector2 Position, Rectangle CollisionBox)
        {

            GetCollider = CollisionBox;
            GetPosition = Position;
            

        }

The same is true for the enemy Tracker class

public Tracker(Vector2 Position, Rectangle CollisionBox)
{
GetCollider = CollisionBox;
GetPosition = Position;
}

How would I get it so that the Tracker class basically follows the Player class when nearby?

I don’t entirely understand your code (the name of a variable or field should be a noun, never a command (“GetCollider” is a confusing name for a field)),

… but ONE tracking approach would be (in pseudocode):

In game Initialize():

  • tracker.SetTarget(player); // which assigns “player” to a “_target” private field inside Tracker

In tracker.Update(GameTime gameTime):

var toTarget = _target.Position - Position;
if (toTarget .Length <= MinDistanceToFollowTarget)
{
// target in reach
var targetDirection = toTarget;
targetDirection.Normalize();
_velocity = targetDirection * FollowSpeed; // set private field _velocity to pursuit the target
}
else
{
_velocity = Vector2.Zero; // target too far, stop moving…
}
// integrate movement for the current frame:
Position += _velocity * gameTime.ElapsedGameTime.TotalSeconds;

… where MinDistanceToFollowTarget and FollowSpeed are constants you need to declare and choose a value for that fits your needs

So the tracker.update would be in the Tracker Class or the game class?

cleanest code would be if indeed that update code is in the tracker class yes. and in your game class, you can instantiate a tracker and call tracker.update from game.update

1 Like