Search code examples
c#unity-game-enginegame-physics

Speed change depending on distance in Unity?


I'm using var heading = target.position - player.position; to calculate a Vector3 that shows the heading from my enemy to my player, but apparently the speed differs when the distance is different. So when it's really close it will go really slow and when it's far away it will go pretty fast. Is there a way of making it go the same speed all the time? I'm using rigidbody.velocity btw.

This is the full move towards player script:

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {
public Rigidbody rb;
public bool yaonah = true;
public Transform player;
public float speed = 100;

// Use this for initialization
void Start () {
    rb = GetComponent<Rigidbody>();

}

// Update is called once per frame
void Update () {
    if (yaonah) {
      StartCoroutine(Wait(2));
    }

}

void Move()
{
    Debug.Log(rb.velocity);
    //Vector3 dir = Random.insideUnitCircle * 5;
    var pdir = player.position - transform.position;
    rb.velocity = pdir; //Player Direction
    Debug.Log("HEY");
    Debug.Log(pdir + "PlayerPos");
}
IEnumerator Wait(float waittime)
{
    yaonah = false;
    Move();
    yield return new WaitForSeconds(waittime);
    yaonah = true;
}
}

Solution

  • so instead of using

    var pdir = player.position - transform.position;
    rb.velocity = pdir; //Player Direction
    

    try to use something like this:

    var pDir = player.position - transform.position;
    pDir = (1f/pDir.magniude()) * pDir; //This Vector3 has now the Length 1
    rb.velocity = pDir; 
    //if you want to make him faster, 
    //multiply this vector with some value of your choice
    

    I hope, this helps