2D platformer enemy defies physics with Vector2.MoveTowards. Alternative?

I’ve been working on a game for a school project and I’m currently trying to figure out a basic enemy AI. Right now I’m using a MoveTowards to make the enemy walk towards the player when the player is within range, and return to it’s spawnpoint when the player is out of range or dead.

    public float maxSpeed = 10;

    private bool grounded = false;
    public Transform groundCheck;
    private float groundRadius = 0.2f;
    public LayerMask whatIsGround;

    public float jumpForce = 700f;

    public Transform target;
    public Transform spawn;

void FixedUpdate () {
        grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
        animate.SetBool ("Ground",grounded);
        animate.SetFloat ("vSpeed", rb.velocity.y);

        float step = maxSpeed * Time.deltaTime;

        rb.velocity = new Vector2 (step * maxSpeed, rb.velocity.y);
        animate.SetFloat("Speed", Mathf.Abs(rb.velocity.y));
}

void OnTriggerStay2D (Collider2D other){
        float step = maxSpeed;
        if (other.gameObject.CompareTag ("target")) {
            transform.position = Vector2.MoveTowards (transform.position, target.position, step);
        }
    }

This is the code that currently controls my enemy. When my player is within range of my enemy, it flies towards the player, kills it, and hovers back to it’s spawn. Any help would be appreciated!

It’s not the Vector2.MoveTowards that is making your object defy physics.

It’s the fact that you set the position of the Transform, rather than setting the velocity.

Setting the position of the transform ignores all physics and just teleports to the point you tell it to go to.

1 Like

I changed the code to:

rb.velocity = Vector2.MoveTowards (transform.position, target.position, step);

and the enemy began to fly away from the player when it came within range. I also multiplied the MoveTowards by -1 and he still flew towards the player and when near the player it would come to a stop and hover next to it.

It’s not clear what you want exactly. Most people do a distance check for when they want something to go into attack mode. Move towards shouldn’t make the character fly anywhere. I do something like this. A distance check, and then a coroutine that moves the character toward the destination. When he gets there, the coroutine ends. What type of physics is being ignored? Triggers require a rigidbody, but you can set it to kinematic.

If I were to maybe guess - it’s that you don’t want it to fly? For that, you just don’t move on the y-axis. :slight_smile:

If it’s something else, you haven’t explained it well, sorry. :slight_smile: