- Home /
Custom Gravity
I have been working on a custom gravity system for some planets I am fiddling with, I have tried every tutorial on how to make this work but it just doesn't work:
//g.offset is the middle of the gravitational pull
foreach (Collider col in Physics.OverlapSphere(g.offset, g.Radius))
{
if (col.attachedRigidbody != null)
{
Rigidbody body = col.attachedRigidbody;
body.freezeRotation = true;
body.useGravity = false;
body.AddForce(9.81f * (g.offset - body.position) * Time.deltaTime);
RaycastHit hit;
if (Physics.Linecast(body.transform.position, g.offset, out hit))
{
body.transform.eulerAngles = hit.normal;
}
}
}
I have checked that the normal is facing the correct way and it is, but the object seems to be facing the opposite direction compared to the normal.
Answer by Bunny83 · Oct 31, 2015 at 02:57 PM
First of all if the planet is a sphere you could simply use this as normal:
Vector3 normal = (body.position - g.offset).normalized;
However if you need it to be more precise if the surface isn't a perfect sphere you can use your line cast approach as well.
This line however:
body.transform.eulerAngles = hit.normal;
makes no sense. EulerAngles represents the rotation of the objects in degree. Your normal vector is just a direction vector with a length of 1f.
To get a proper rotation from the normal there are several ways, but the most robust would be to project the objects current forward direction onto the tangent plane at the current position of the player on the surface and use LookRotation to calculate the appropriate rotation.
Vector3 fwd = body.transform.forward;
fwd = fwd - Vector3.Project(fwd, normal);
body.transform.rotation = Quaternion.LookRotation(fwd, normal);
Your answer
Follow this Question
Related Questions
Simulating magnetic shoes? 0 Answers
I have a planetary gravity script; how do I make the object speed up? 1 Answer
Tranform Animation Curve ruins Gravity 1 Answer
Rigidbody velocity disables gravity 1 Answer
Trying to walk on a wall 0 Answers