在 Unity 中创建 Cube 对象并附加脚本,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeRotation : MonoBehaviour
{
public float rotationSpeed = 50f; //控制旋转的速度
public Vector3 rotationAxis = Vector3.up; //自定义旋转轴向量
void Update()
{
//标准化旋转轴向量,可删除
rotationAxis.Normalize();
//在每一帧更新中旋转 Cube
transform.Rotate(rotationAxis, rotationSpeed * Time.deltaTime);
}
}
在 Inspector 窗口中,小伙伴们可以设置 rotationAxis 字段的值来定义旋转的自定义方向。例如,你可以将其设置为 Vector3.forward,使 Cube 沿着 Z 轴旋转。小伙伴们还可以设置 rotationSpeed 字段的值,以控制旋转的速度。
“rotationAxis.Normalize()”可删除,在某些情况下,标准化旋转轴向量是必要的,特别是当你希望确保旋转轴向量的长度为1时。标准化旋转轴向量可以保持旋转的一致性和可预测性。
当旋转轴向量的长度不为1时,旋转速度可能会受到长度的影响,导致旋转速度不均匀或不符合预期。通过标准化旋转轴向量,你可以确保旋转速度与旋转轴向量的长度无关,从而保持旋转的稳定性和一致性。