引导:
最先想到用DOTween插件——但我打算,用脚本实现看看。
目标:
让立方体,围绕Y轴顺时针转60°
实施:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestSelfRotate : MonoBehaviour
{
public bool isCanOpen=false;
void Awake()
{
}
void Start()
{
}
void Update()
{
//if(isCanOpen)
//{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(new Vector3(0, 60, 0)), Time.deltaTime);
Debug.Log(transform.eulerAngles.y);
// if(transform.eulerAngles.y>=60)
// {
// isCanOpen = false;
// Debug.Log("GoodDay");
// }
//}
}
}
但是,这样Update会一直执行Quaternion.Slerp这个函数,造成空耗资源——于是想给脚本加bool变量,当立方体转到60°,就不执行Quaternion.Slerp这个函数了
但发现,即使它转到了60°,前一个图中绿色的 Debug.Log(transform.eulerAngles);依旧在执行,而不进入
if(transform.eulerAngles.y>=60)这个if判断
{
isCanOpen = false;
Debug.Log(“GoodDay”);
}
单独打印
发现它根本到不了60,那就让它转到大于等于59°时停止吧。
函数成功结束,不再进入if(isCanOpen)语句
总结:
1、确定时间内,转动确定角度用
(注意红框处,一定要这样写。)
2、想让它在一定角度停止执行以上函数,最好让它在该角度减去1度的角度停止,因为它根本转不到目标角度。
可直接复制的代码:
/*
*
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestSelfRotate : MonoBehaviour
{
public bool isCanOpen=true;
void Awake()
{
}
void Start()
{
}
void Update()
{
if (isCanOpen)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(new Vector3(0, 60, 0)), Time.deltaTime);
Debug.Log(transform.eulerAngles.y);
if (transform.eulerAngles.y >= 59)
{
//Debug.Log(transform.eulerAngles);
isCanOpen = false;
Debug.Log("GoodDay");
}
}
}
}
补充:
物体在固定时间时间内,转向某物体。
Quaternion TargetRotation = Quaternion.LookRotation(m_Target.transform.position - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, TargetRotation, Time.deltaTime * 2.5f);