视频效果:本质上做的简谐运动
代码:
public class FloatObj : MonoBehaviour
{
[Header("旋转速度")]
public float rSpeed = 2;
[Header("上下移动限制")]
public float radius = 0.8f;
[Header("每秒移动的角度变化")]
public float perDegree = 10f;
//移动后的位置
private Vector3 pos;
//弧度
private float degree = 0;
private float startY;
private void Start()
{
pos = transform.position;
startY = pos.y;
}
private void Update()
{
degree += perDegree*Time.deltaTime;
//防溢出
if (degree > 360)
{
degree -= 360;
}
pos.y = startY + Mathf.Cos(degree*Mathf.Deg2Rad) * radius;
transform.position = pos;
//漂浮物可以自带一点点旋转
transform.RotateAround(transform.position,transform.up,rSpeed * Time.deltaTime); //绕y轴旋转
}
}