如何在 C# (Unity) 中设置对象的最大旋转
How to set a max rotation on an object in C# (Unity)
我正在尝试让 space 船在向上行驶时向上倾斜或在下落时向下倾斜,但我被卡住了,这是我目前所做的
if (Input.GetKey(KeyCode.Space)) //If spacebar pressed
{
playerRb.AddForce(Vector3.up * floatForce, ForceMode.Impulse); // Add force upwards to player
}
// Rotates upwards
if (Input.GetKey(KeyCode.Space))
{
if (transform.rotation.x != -maxRotation)
{
transform.Rotate(-rotationSpeed, 0f, 0f * Time.deltaTime);
transform.Rotate(-maxRotation, 0f, 0f);
}
}
当我按下 space 条时它会无限旋转...
有什么帮助吗?
谢谢
如果要限制对象的旋转,可以修改eulerAngles
属性值。
例子
以下脚本采用几个向量并确保对象旋转保持在它们的 x、y、z 值之间的范围内。
using UnityEngine;
public class RotationLimitter : MonoBehaviour
{
[SerializeField]
private bool runOnUpdate = true;
[SerializeField]
private bool runOnLateUpdate = false;
[SerializeField]
private bool runOnFixedUpdate = false;
[Space]
[SerializeField]
private Vector3 minRotation = Vector3.zero;
[SerializeField]
private Vector3 maxRotation = Vector3.zero;
private void Update()
{
if (runOnUpdate)
LimitRotation();
}
private void LateUpdate()
{
if (runOnLateUpdate)
LimitRotation();
}
private void FixedUpdate()
{
if (runOnFixedUpdate)
LimitRotation();
}
private void LimitRotation()
{
float x = Mathf.Clamp(transform.eulerAngles.x, minRotation.x, maxRotation.x);
float y = Mathf.Clamp(transform.eulerAngles.y, minRotation.y, maxRotation.y);
float z = Mathf.Clamp(transform.eulerAngles.z, minRotation.z, maxRotation.z);
transform.eulerAngles = new Vector3(x, y, z);
}
}
我正在尝试让 space 船在向上行驶时向上倾斜或在下落时向下倾斜,但我被卡住了,这是我目前所做的
if (Input.GetKey(KeyCode.Space)) //If spacebar pressed
{
playerRb.AddForce(Vector3.up * floatForce, ForceMode.Impulse); // Add force upwards to player
}
// Rotates upwards
if (Input.GetKey(KeyCode.Space))
{
if (transform.rotation.x != -maxRotation)
{
transform.Rotate(-rotationSpeed, 0f, 0f * Time.deltaTime);
transform.Rotate(-maxRotation, 0f, 0f);
}
}
当我按下 space 条时它会无限旋转...
有什么帮助吗? 谢谢
如果要限制对象的旋转,可以修改eulerAngles
属性值。
例子
以下脚本采用几个向量并确保对象旋转保持在它们的 x、y、z 值之间的范围内。
using UnityEngine;
public class RotationLimitter : MonoBehaviour
{
[SerializeField]
private bool runOnUpdate = true;
[SerializeField]
private bool runOnLateUpdate = false;
[SerializeField]
private bool runOnFixedUpdate = false;
[Space]
[SerializeField]
private Vector3 minRotation = Vector3.zero;
[SerializeField]
private Vector3 maxRotation = Vector3.zero;
private void Update()
{
if (runOnUpdate)
LimitRotation();
}
private void LateUpdate()
{
if (runOnLateUpdate)
LimitRotation();
}
private void FixedUpdate()
{
if (runOnFixedUpdate)
LimitRotation();
}
private void LimitRotation()
{
float x = Mathf.Clamp(transform.eulerAngles.x, minRotation.x, maxRotation.x);
float y = Mathf.Clamp(transform.eulerAngles.y, minRotation.y, maxRotation.y);
float z = Mathf.Clamp(transform.eulerAngles.z, minRotation.z, maxRotation.z);
transform.eulerAngles = new Vector3(x, y, z);
}
}