Robertgold
Robertgold

Reputation: 225

Ai spins all the time when collision occurs

Have a simple AI thats follows the player when in range and randomly moves the ai around when it's not in the player range. When the AI hits a wall and is out of the players range it starts to spin all the time. Can't work out why it keeps doing so.

I may be missing a simple thing... Many thanks for any help.

void Update()
{
    Target = GameObject.FindGameObjectWithTag("Player");

    if (Vector3.Distance(Target.transform.position, transform.position) < 25)
    {
        followPlayer();
    }
    else
    {
        randomMovement();
    }

}

public void followPlayer()
{

    if (Vector3.Distance(transform.position, Target.transform.position) >= MinDist)
    {

        transform.position += transform.forward * MoveSpeed * Time.deltaTime;
        transform.LookAt(Target.transform);


        if (Vector3.Distance(transform.position, Target.transform.position) <= MaxDist)
        {
        }

    }
    else
    {

    }

}

public void randomMovement()
{
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;
    transform.Rotate(RandomDirection * Time.deltaTime * 10.0f);

}

void OnCollisionEnter(Collision col)
{
    bool hasTurned = false;

    if (col.transform.gameObject.name != "Terrain")
    {
        if(hasTurned == false)
        {
            RandomDirection = new Vector3(0, Mathf.Sin(TimeBetween) * (RotationRange / 2) + OriginalDirection, 0);
            randomMovement();
            hasTurned = true;
        }
        else
        {
            randomMovement();
            hasTurned = false;
        }


        Debug.Log("Hit");
    }

Upvotes: 1

Views: 92

Answers (1)

ryeMoss
ryeMoss

Reputation: 4343

The reason it is continuously spinning is because you are continuously calling randomMovement() in your Update() which continously applies a rotation to your object with Rotate(). It sounds like what you are instead trying to do is have the object wander aimlessly every few seconds. You could do this by implementing on timer on your randomMovement() so that every few seconds, it generates a new rotation(similar to what you have in the onCollision). Example below.

float t = 0;
public void randomMovement()
{
    transform.position += transform.forward * MoveSpeed * Time.deltaTime;

    t += Time.deltaTime;
    if (t > 3f) // set to a new rotation every 3 seconds.
    {
        t = 0; // reset timer
        RandomDirection = new Vector3(0, Random.Range(0f, 360f), 0); // turn towards random direction

        transform.Rotate(RandomDirection);
    }
}

Upvotes: 1

Related Questions