我想创造一种效果,就像对象环顾四周。 就像在四处巡视。在这种情况下,他正看着窗户,所以想法就是使他看起来像在向外看。
这是Navi看着窗口的屏幕截图: 摄像头位于窗口的外面,在Navi面上向前看:
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);
}
}
}
我只想在y轴上随机旋转90度到270度之间的对象。因此,看起来该对象在向左右两侧看。
但是现在对象只是在向左一个方向不停地旋转。
答案 0 :(得分:1)
一种方法是使用协程每隔很长时间生成一次随机旋转,然后随时间逐渐变化:
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;
}
}
}
然后您可以通过以下方式调用它:
StartCoroutine("DoLookAround");
并用
停止StopCoroutine("DoLookAround");