制作一个能够跟随物体的滑块
想要的效果:
需求分析:
- 我们想要这个滑块跟随这个球移动
- 自身被限制在这轨道上
- 不能让滑块离开这个轨道,而且还要跟随这个球
用的算法来实现这个需求
这相当于已知ABC三个点的坐标,求C点垂直于AB之间的坐标,也就是D点的坐标
假设mAPoint是起始点,mBPoint是结束点,mCurrentPoint是当前移动的点,返回的我们映射的点
我们需要先得到AB两点的向量:
Vector3 vectorAB = mBPoint - mAPoint;
计算点积
float dotProduct = vectorAB.x * (mCurrentPoint.x - mAPoint.x) + vectorAB.y * (mCurrentPoint.y - mAPoint.y) + vectorAB.z * (mCurrentPoint.z - mAPoint.z);
float lengthSquared = vectorAB.x * vectorAB.x + vectorAB.y * vectorAB.y + vectorAB.z * vectorAB.z;
限制不能超过两点之外
if (dotProduct > lengthSquared) dotProduct = lengthSquared; if (dotProduct < 0) dotProduct = 0;
映射计算位置
Vector3 PointA = mAPoint + vectorAB * dotProduct / lengthSquared;
Vector3 PointB = mCurrentPoint + (PointA - mCurrentPoint);
return PointB;
实现的效果:
我们得到了我们想要的效果!
在一个面上就更加容易了
只需要一个点和向量就可以
假设mNormal是方向,mTargetPoint是位置,mCurrentPoint是当前移动的点
Vector3 projection = mCurrentPoint - Vector3.Dot(mCurrentPoint - mTargetPoint, mNormal) * mNormal;
Demo下载地址