I was playing F-ZeroGX the other day and wondered how I’d do something similar. Basically, in GX, the race courses in a few levels are tubes and you can go all around them.
How would I apply gravity so there’s a constant force pushing down on each face of the tube?
Once I’ve figured this out I can see loads of other uses for it…
The easiest way to do it would be to apply gravity relative to the up vector (green axis) of the object
var gravity = 9.81;
function FixedUpdate ()
{
rigidbody.AddForce(-Vector3.up * rigidbody.mass * gravity);
}
This might have some issues if the object bounces off walls and starts rotating, since it will change the gravity direction in that case.
The other way to do it is to determine the position relative to the tube. And apply the force so it goes outwards. Basically the direction from the center of the tube to the position of the vehicle.
If you use a chain of line segments along the middle of the tube (probably defined by an array of points), you can get the nearest point on the line segment by looping through the array and use Mathfx.NearestPointStrict from the Wiki (http://www.unifycommunity.com/wiki/index.php?title=Mathfx) to get the point the object should gravitate towards.
I used something similar for track movement in Botbuilder; most of this code is copied and pasted from that. It also requires at least 2 points in its current form, otherwise bad things probably happen.
var TrackPos : Vector3[];
var gravity = 9.81;
var shortestDist : float = 999999.0;
var sdi : int = 0;
for (s=0;s<TrackPos.length-1;s++) {
var thePoint = Mathfx.NearestPointStrict(TrackPos[s], TrackPos[s+1], targetObj.position);
var dist = Vector3.Distance(thePoint, targetObj.position);
if (dist < shortestDist) {
shortestDist = dist;
sdi = s;
}
}
gPoint = Mathfx.NearestPointStrict(TrackPos[sdi], TrackPos[sdi+1], targetObj.position);
rigidbody.AddForce((gPoint - transform.position).Normalized()*gravity*rigibody.mass;
I’ve been wondering about something similar, a “half pipe” as in snowboarding or skateboarding. In this case it’s centrifugal force that keeps the rider from falling down. Anyone played with this?
Else you can have an empty gameObject following the car but staying in the center of the tube (you might have issues if for example you have different sizes of tubes) and this gameObject will apply an ExplosionForce (see: Unity - Scripting API: Rigidbody.AddExplosionForce) to push the car on the road.