1
\$\begingroup\$

I am trying to come up with a smooth wandering motion for my game-object using Unity. What I currently doing is rotate the object by some random angle calculated every 1.5 second delay. But I am aiming getting a smooth rotation whenever it transitions to a different randomly generated angle.

Below is my script attached to my character.

 void Update () {
     if (canWander && (currTime + delay < Time.time)){
        changeAngle();
        currTime = Time.time;
     }
     if(canWander){
        Wander();
     }
}

private void changeAngle(){
    float prevPosY = transform.position.y;
    Vector3 waypoint = Random.insideUnitSphere + new Vector3(10,prevPosY,10);  //waypoints are generated based on random unit sphere + ( bounds of the plane they are on )
    Vector3 relative = transform.InverseTransformPoint (waypoint);
    float angle = Mathf.Atan2 (relative.x, relative.z) * Mathf.Rad2Deg;
    transform.Rotate (0, angle, 0);
}

private void Wander(){
    transform.position += transform.forward * Time.deltaTime * acceleration;
    if (acceleration < maxSpeed) {
        acceleration += 0.5f;       
    }
}

So the character wanders with newly generated random angles every time but its not a smooth transition. It suddenly transitions to the new angle and it does not feel realistic at all. What could I possibly change with my current code to make it more smooth and realistic?

\$\endgroup\$
3
\$\begingroup\$

When you set the new angle that you want to rotate to, use that as a target rotation, and then in Update() you can continually interpolate the character's current rotation to the target rotation using Mathf.LerpAngle. The rotation speed variable will be an arbitrary float that controls how quickly the character moves to the target angle.

void Update() {
    // ...
    transform.eulerAngles = new Vector3(0, Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, Time.deltaTime * rotationSpeed), 0);
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.