Unity makes a slider to follow the object, the object follows the object on a straight line, the coordinates of the three points ABC are known, find the coordinates of point C perpendicular to AB, and the mapping between point C and AB

Make a slider that can follow an object

The desired effect:

insert image description here

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.
insert image description here
insert image description here
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:

Please add a picture description

We got the effect we wanted!

Demo download address

Guess you like

Origin blog.csdn.net/CTangZe/article/details/131083999