Home > Mobile >  How to make an enemy follow the player with momentum in Unity?
How to make an enemy follow the player with momentum in Unity?

Time:06-30

I am a beginner in Unity developing a 2D top-down mobile game. I am trying to create an enemy movement script that mimics the pattern of the leech enemy below:

enter image description here

This enemy is constantly trying to move towards the player but even though it can move quite quickly, due to its momentum, you are able to kite it as it cannot make a sharp turn without first taking some time to build speed in another direction.

I have created a script for enemies to constantly be targeting the player based on the player's current position but it is too difficult to dodge my enemies as they are able to turn instantly when the player does and maintain a constant speed. I would like to balance them to be more like this leech enemy so the player can dodge them by taking advantage of the enemy's current momentum with proper timing. How can I create this momentum effect for my enemies?

CodePudding user response:

If you're using Unity's physics here's a way to do this nicely:

Walkable.cs

Create a modular component that all walkable game objects will use. The purpose of the component is to keep the object moving in the specified direction while stabilising the forces. It uses the values you configure in the inspector for speed and force. It does the movement inside of FixedUpdate as physics movement require it.

public class Walkable : MonoBehaviour {

    private const float ForcePower = 10f;

    public new Rigidbody2D rigidbody;

    public float speed = 2f;
    public float force = 2f;

    private Vector2 direction;

    public void MoveTo (Vector2 direction) {
        this.direction = direction;
    }

    public void Stop() {
        MoveTo(Vector2.zero);
    }

    private void FixedUpdate() {
        var desiredVelocity = direction * speed;
        var deltaVelocity = desiredVelocity - rigidbody.velocity;
        Vector3 moveForce = deltaVelocity * (force * ForcePower * Time.fixedDeltaTime);
        rigidbody.AddForce(moveForce);
    }
}

Character.cs

This is a simple example of character that will follow a target. Notice how all it's doing is passing the direction to the walkable from inside an Update function.

public class Character : MonoBehaviour {

    public Transform target;
    public Walkable walkable;

    private void Update() {
        var directionTowardsTarget = (target.position - this.transform.position).normalized;
        walkable.MoveTo(directionTowardsTarget);
    }
}

Configurations

By configuring move and force variables you can get a variety of movement styles, some that can move fast but take a long time to ramp up, some that ramp up fast but move slowly overall.

You can also play around with with mass and linear drag on the Rigidbody2D to get even more control over the movement style.

  • Related