之前试过很多方法,比如
①,UI坐标错开,进行上下位移,发现效果很僵硬
②,又尝试加上差值曲线进行移动,发现效果虽然不僵硬了,但是移动效果很差
③,尝试使用缓动,效果不理想
最后采用了以下办法
使用三角函数曲线进行上下移动,配合水平移动即可实现。
三角函数使用代码如下
using UnityEngine;
using System.Collections;
public class Floating : MonoBehaviour
{
float radian = 0; // 弧度
float perRadian = 0.03f; // 每次变化的弧度
float radius = 0.8f; // 半径,决定UI上下移动高度
Vector3 tempPos; // 开始时候的坐标
// Use this for initialization
void Start()
{
tempPos = transform.position; // 将最初的位置保存到tempPos
}
// Update is called once per frame
void Update()
{
radian += perRadian; // 弧度每次加0.03
float dy = Mathf.Cos(radian) * radius; // dy是y轴的变量,可以使用sin
transform.position = tempPos + new Vector3(0, dy, 0);
}