Unity | 物体上下浮动效果
程序员文章站
2022-07-13 22:29:47
...
原文:Making Objects Float Up & Down in Unity
// Floater v0.0.2
// by Donovan Keith
//
// [MIT License](https://opensource.org/licenses/MIT)
using UnityEngine;
using System.Collections;
// Makes objects float up & down while gently spinning.
public class Floater : MonoBehaviour {
// User Inputs
public float degreesPerSecond = 15.0f;
public float amplitude = 0.5f;
public float frequency = 1f;
// Position Storage Variables
Vector3 posOffset = new Vector3 ();
Vector3 tempPos = new Vector3 ();
// Use this for initialization
void Start () {
// Store the starting position & rotation of the object
posOffset = transform.position;
}
// Update is called once per frame
void Update () {
// Spin object around Y-Axis
transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);
// Float up/down with a Sin()
tempPos = posOffset;
tempPos.y += Mathf.Sin (Time.fixedTime * Mathf.PI * frequency) * amplitude;
transform.position = tempPos;
}
}
思路
记录物体原本的位置,在此基础上使用Mathf.Sin()
函数,让物体上下浮动(类似为横波的简谐运动)
1 浮动
posOffset
为物体的初始位置,先记录下来
修改其y
即数值方向的坐标:tempPos.y += Mathf.Sin(...)
(Time.fixedTime * Mathf.PI * frequency)
和 amplitude
相当于频率(快慢)和幅度(强度)
2 旋转
transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);
绕何轴旋转,将何轴以外置为0
效果
下一篇: 结构体内存对齐与大小端问题