Daniel Lip
Daniel Lip

Reputation: 11325

How can I rotate an object from on one axis randomly between two directions?

I want to create effect like the object is looking around. Like it's inspecting around. In this he is looking at a window so the idea is to make like he is looking the view outside.

This is a screenshot of the Navi looking at the window : The camera is positioned out of the window looking forward on the Navi face:

Navi is looking at the window the view outside

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemAction : MonoBehaviour
{
    public float xAngle, yAngle, zAngle;
    public float speed;
    public camMouseLook mouselook;
    public GameObject lockedRoomCamera;
    public Camera playerCamera;
    public GameObject navi;
    private bool torotate = false;

    public void Init()
    {
        navi.transform.parent = null;
        navi.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
        navi.transform.Rotate(new Vector3(0, 180, 0));
        PlayerController.disablePlayerController = true;
        mouselook.enabled = false;
        playerCamera.enabled = false;
        lockedRoomCamera.SetActive(true);
        torotate = true;

    }

    private void Update()
    {
        if(torotate == true)
        {
            navi.transform.Rotate(xAngle, Random.Range(90, 270) * speed * Time.deltaTime, zAngle, Space.Self);
        }
    }
}

I want to rotate the object only on the y axis randomly between 90 degrees and 270 degrees. So it will looks like the object is looking to the sides left and right.

But now the object is just spinning nonstop on one direction to the left.

Upvotes: 1

Views: 188

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

One way is to use a coroutine to generate random rotations every so often and then lerp to them over time:

IEnumerator DoLookAround() 
{
    float lookPeriod = 5f; // change look every 5 seconds
    float maxRotationSpeed = 90f; // turn no faster than 90 degrees per second
    Vector3 neutralForward = transform.forward;

    while(true) 
    {
        float timeToNextLook = lookPeriod;

        while (timeToNextLook > 0) {
            // Get random offset from forward
            float targetYRotation = Random.Range(-90f, 90f);

            // calculate target rotation
            Quaternion targetRotation = Quaternion.LookRotation(neutralForward, transform.up) 
                                       * Quaternion.AngleAxis(targetYRotation, Vector3.up);

            // rotate towards target limited by speed
            Quaternion newRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, maxRotationSpeed * Time.deltaTime);


            timeToNextLook -= Time.deltaTime;
            yield return null;
        }
    }
}

Then you can call it with:

StartCoroutine("DoLookAround");

and stop it with

StopCoroutine("DoLookAround");

Upvotes: 1

Related Questions