Make a slider that can follow an object
The desired effect:
demand analysis:
- We want the slider to follow the ball
- self is confined to this orbit
- Can't let the slider leave this track, but also follow the ball
The algorithm used to achieve this requirement
This is equivalent to knowing the coordinates of three points ABC, and finding the coordinates of point C perpendicular to AB, that is, the coordinates of point D.
We need to get the vector of two points AB first:
Vector3 vectorAB = mPointB - mPointA;
Then calculate the length of point C between two points AB
float dotProduct = vectorAB.x * (mPointC.x - mPointA.x) + vectorAB.y * (mPointA.z - mPointA.y) + vectorAB.z * (mPointC.z - mPointA.z);
float lengthSquared = vectorAB.x * vectorAB.x + vectorAB.y * vectorAB.y + vectorAB.z * vectorAB.z;
The limit cannot exceed two points
if (dotProduct > lengthSquared) dotProduct = lengthSquared; if (dotProduct < 0) dotProduct = 0;
Map calculation location
mPointA + vectorAB * dotProduct / lengthSquared;
Achieved effect:
We got the effect we wanted!
Demo download address