- Home /
-Accurate- following of a Bézier curve
I'm making a 2.5D sidescroller, and the path the player character follows isn't one straight line. It's composed of quadratic, symmetrical Bézier curves. Here's the code that defines the curve, sets the player char's velocity, and detects which curve they are on.
t = Vector3.Project(rigidbody.position-nodes[n].position, nodes[n+1].position-nodes[n].position).magnitude / (nodes[n+1].position-nodes[n].position).magnitude;
//t is where the player is between the starting point and the ending point
//on a scale of 0 to 1.
Vector3 p0 = nodes[n].position;//the starting point of the curve
Vector3 p2 = nodes[n+1].position;//the ending point of the curve
Vector3 p1 = (p0 + p2)/2 + new Vector3(-(p2 - p0).z, 0, (p2 - p0).x).normalized * nodes[n].knob;//the point that determines how curvy the curve is. It's always perpendicular to the line between p0 and p2, as the curves should be symmetrical.
velocity = new Vector3(1, 0, 2*(1-t)*(p1.z-p0.z)+2*t*(p2.z-p1.z)).normalized*3f;
//The Z argument is the derivative of the quadratic curve, which should be a good
//way to set a velocity vector. But that is probably where the problem lies.
rigidbody.rotation = Quaternion.LookRotation(velocity);
//The code below sets which nodes (the points where a curve ends and another begins) the player
//is between. The origin of the rigidbody is 1 unit above the ground.
if ((rigidbody.position - nodes[n+1].position).magnitude < 0.99f
&& (rigidbody.position - nodes[n].position).magnitude >= 0.99f
&& wasGoingRight)
{
if (n == nodes.Length - 1)
{
rigidbody.position = nodes[n].position + new Vector3(0, 0.94f, 0);
velocity = Vector3.zero;
}
else
{
rigidbody.position = nodes[n+1].position + new Vector3(0, 0.94f, 0);
n++;
}
}
if ((rigidbody.position - nodes[n].position).magnitude < 0.99f
&& (rigidbody.position - nodes[n+1].position).magnitude >= 0.99f
&& !wasGoingRight)
{
if (n == 0)
{
rigidbody.position = nodes[n].position + new Vector3(0, 0.94f, 0);
velocity = Vector3.zero;
}
else
{
rigidbody.position = nodes[n].position + new Vector3(0, 0.94f, 0);
n--;
}
}
In the game, the character moves as if they're on a completely different curve. As I stated above, the problem is probably in the velocity line.
Also, is there a way to change the origin of the rigidbody? It's awkwardly in front of the model.
Your answer
Follow this Question
Related Questions
Moving rigidbody along spline, and being able to use physics 1 Answer
Rotate non-kinematic 2D rigidbody on different axis 0 Answers
How can I make a Lerp move in an arc instead of a straight line? 2 Answers
What is the best way to make an AI throw something 2 Answers
Projectile launch insufficient velocity 2 Answers