Magnetic or Gravity set to 3D track

I have a 3D racetrack that switches around to all sides, so normal gravity does not help me.

I used the next line of code to test things on a sphere.

transform.rigidbody.velocity += (CenterAx.transform.position - this.transform.position).normalized * 60 * Time.deltaTime;

However this only works as most things that I’ve found searching for a solution. As a gravitational/magnetic field towards the center point at CenterAx. Which will float the car to the center space of the track :wink:

I would like to have gravity set towards the track.

track: https://imageshack.com/i/eyluBbcNp

as you can see the track goes in every direction. The track is a .fbx model with an animator

So how to set dynamic gravity to the track?

edit:

I have found this

It includes a dropbox link to the playercontroller.

It gives me gravity, but not the results that I need yet. This because when I add speed to my vehicle the vehicle becomes very bumpy and when leaving the track with some speed the vehicle floats off into space.

I already increased the gravity to a point that when I further increase it the vehicle will just be pushed through the track.

So ideas anyone?

What you probably want to use is ConstantForce. It’s a component that you add to an object with a rigidbody, that applies a constant force. It works pretty much in the same way as gravity, but you can set the direction yourself.

Then, on Update or FixedUpdate or whatever, you change the ConstantForce to be a vector pointing from your vehicle down to the track. To find where the track is, give it a collider and use ClosestPointOnBounds.

So you will have something like this on your vehicle script:

ConstantForce localGravity;
float localGravityForce = 9.81f; //Mess with this to get something that works
Collider trackCollider;

void Start() {
    localGravity = GetComponent<ConstantForce>();
    trackCollider = ???//grab the track collider in whatever way works
}

void Update() {
    Vector3 trackPos = trackCollider.ClosestPointOnBounds(transform.position);
    Vector3 wantedGravity = trackPos - transform.position;
    localGravity.force = wantedGravity;
}

This isn’t tested, but it should give something quite like the F-Zero thing you’re looking for. Probably.

The stuff that I found mentioned in the question edit part gives me something to work with and is in essence the answer to my question.