Unity中如何设计出一个物体随移动方向转向的脚本
可以使用以下代码:
using UnityEngine;
public class RotateTowardsMovement : MonoBehaviour
{
public float rotationSpeed = 10f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (rb.velocity.magnitude > 0)
{
float angle = Mathf.Atan2(rb.velocity.y, rb.velocity.x) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
}
解释一下代码:
rotationSpeed是旋转速度,可以在 Inspector 面板中设置。rb是物体的 Rigidbody2D 组件,用于获取物体的速度。FixedUpdate是固定时间间隔执行的函数,用于更新物体的旋转。if语句检查物体是否正在移动,如果是,则计算出物体的移动方向,并计算出需要旋转的角度。Quaternion.Euler用于将角度转换为旋转矩阵。Quaternion.Slerp用于平滑地旋转物体,避免旋转过程中出现跳动。
原文地址: https://www.cveoy.top/t/topic/bHqs 著作权归作者所有。请勿转载和采集!