有一道题:一个物体围绕原点(0,0)做匀速圆周运动。t1时物体位置为(x1,y1),已知物体的角速度为 w,围绕半径为 r。求经过时间t后,物体在圆周上位置(x,y)。
求得:
- x = r * sin(w * t)
- y = r * cos(w * t)
using UnityEngine;
public class RotateAround : MonoBehaviour {
public Transform aroundPoint;//围绕的物体
public float angularSpeed;//角速度
public float aroundRadius;//半径
private float angled;
void Start () {
//设置物体初始位置为围绕物体的正前方距离为半径的点
Vector3 p = aroundPoint.rotation * Vector3.forward * aroundRadius;
transform.position = new Vector3(p.x, aroundPoint.position.y, p.z);
}
void Update () {
angled += (angularSpeed * Time.deltaTime) % 360;//累加已经转过的角度
float posX = aroundRadius * Mathf.Sin(angled * Mathf.Deg2Rad);//计算x位置
float posZ = aroundRadius * Mathf.Cos(angled * Mathf.Deg2Rad);//计算y位置
transform.position = new Vector3(posX, 0, posZ) + aroundPoint.position;//更新位置
}
}
本文介绍如何使用Unity实现物体围绕指定点进行匀速圆周运动,通过设定角速度和半径,利用Sin和Cos函数计算物体在圆周上的位置,并提供了完整的C#脚本示例。

401

被折叠的 条评论
为什么被折叠?



