引:
上个博客中讲述了如何用鼠标拖动面板,但面板的拖动范围并没有得到控制。而且各个面板拖动起来总差点意思,接下来我们通过代码的方式实现两个功能:
- 左右边界控制
- 整板卡位
先看效果:
从图中可以看出,每个面板感觉都想有根弹簧在蹦着。
核心函数
其实这个弹簧功能是由一个函数来实现的。
public static Vector3 Lerp(Vector3 a, Vector3 b, float t);
解释一下这个函数:官网解释
通俗一点讲,第一个参数是我自己的位置,第二个参数是目标位置,第三个位置当成弹性系数就好。从我的位置弹回目标位置。
代码
//1. 左边受限,若往右移,则再弹回
if (this.transform.localPosition.x > 0)
{
//Lerp方法用来做弹簧模拟
this.transform.localPosition = Vector3.Lerp(this.transform.localPosition, Vector3.zero, Time.deltaTime * K);
}
//2. 右边受限
if (this.transform.localPosition.x < -3200)
{
this.transform.localPosition = Vector3.Lerp(this.transform.localPosition, new Vector3(-3200, 0, 0), Time.deltaTime * K);
}
//3. 整版卡位
if(this.transform.localPosition.x < 0 && this.transform.localPosition.x >= -400)
{
this.transform.localPosition = Vector3.Lerp(this.transform.localPosition, Vector3.zero, Time.deltaTime * K);
}
else if(this.transform.localPosition.x < -400 && this.transform.localPosition.x >= -800)
{
this.transform.localPosition = Vector3.Lerp(this.transform.localPosition, new Vector3(-800,0,0), Time.deltaTime * K);
}
整版卡位我只写了第一个面板,后面的面板函数都一样,把里面的参数改下就行了