Production: Follow Player


In the last post we implemented an enemy wave system that can be easily configured by a designer. Today, we’re going to cause enemies to randomly decide to follow the player when they are instantiated.

The Challenge

The challenge is to randomly choose when an enemy should follow the player and apply the new position changes inside of FixedUpdate.

Following The Player

First, an enemy should randomly decide if it should move straight down or follow the player. I’ll do this easily by getting a random float value between 0 and 1 in the Awake m.

private void Awake()
    _followPlayer = Random.Range(0f, 1f) >= 0.7f;

Inside FixedUpdate we’ll follow the player if _followPlayer is true. We get the distance from the target (player) and Normalize it. Then I set the rotate amount based on the cross product of the distance and up vectors. I then set the angular velocity and velocity of the enemy Rigidbody2D.

if (_followPlayer)
    var distanceFromTarget = _player.transform.position - _rigidbody2D.transform.position;

    var rotateAmount = Vector3.Cross(distanceFromTarget, transform.up);
    _rigidbody2D.angularVelocity = -rotateAmount.z * ANGULAR_VELOCITY_SPEED;
    _rigidbody2D.velocity = transform.up * (FOLLOW_SPEED * Time.deltaTime);



That’s it! Now random enemies will decide to follow the player.

Stay tuned for the next post. Take care

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s