Search Unity

transform.LookAt gradually moving A.I. waypoints

Discussion in 'Scripting' started by ravic85, Apr 26, 2015.

  1. ravic85

    ravic85

    Joined:
    Mar 5, 2015
    Posts:
    1
    -----
     
    Last edited: Apr 28, 2015
  2. AngryAnt

    AngryAnt

    Keyboard Operator

    Joined:
    Oct 25, 2005
    Posts:
    3,045
    In stead of using Transform.LookAt directly, use Quaternion.LookRotation to generate the rotational target. Then apply it gradually by using Quaternion.Slerp to interpolate between the current transform.rotation and the target one.
     
  3. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Vector3.RotateTowards will do exactly what you want and you can specify a speed in radians per second (radians, not degrees).

    Code (csharp):
    1.  
    2. Vector3 vector = waypoints[currentwaypointt].position - transform.position;
    3.  
    4. transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, vector, rotationSpeedInRadians * Time.deltaTime, 0.0f));
    5.  
     
  4. tchris

    tchris

    Joined:
    Oct 10, 2012
    Posts:
    133
  5. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Is it possible something else is changing your rotation? Here are the results when I do it (warning: big gif).

    And here's the code:
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class JetFollow : MonoBehaviour
    7. {
    8.    public List<Transform> waypoints;
    9.  
    10.    protected int waypoint;
    11.  
    12.    protected void Start()
    13.    {
    14.      waypoint = 0;
    15.    }
    16.  
    17.    protected void Update()
    18.    {
    19.      Vector3 vector = waypoints[waypoint].position - transform.position;
    20.  
    21.      transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(transform.forward, vector, 0.40f * Time.deltaTime, 0.0f));
    22.      transform.position += transform.forward * 15 * Time.deltaTime;
    23.  
    24.      if(Vector3.Distance(transform.position, waypoints[waypoint].position) <= 4.0f)
    25.      {
    26.        ++waypoint;
    27.  
    28.        if (waypoint >= waypoints.Count)
    29.          waypoint = 0;
    30.      }
    31.    }
    32. }
    33.  
     
  6. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Is 360 degrees per second turn rate what you want? That's pretty fast. You could try lowering it to 90 or 180.

    Also, your character doesn't move forward in the direction they're facing, but heads directly to the next waypoint regardless of rotation. Is this not also contributing to some of the oddity in movement you're seeing?

    Maybe try posting a video or gif if the problem persists.