I'm trying to realize moving on an object round sphere (walk on it), but when it gets to the equator of the sphere, it stops moving.
public Transform planet;
public bool AlignToPlanet;
public float gravityConstant = -9.8f;
void FixedUpdate()
{
Vector3 toCenter = planet.position - transform.position;
toCenter.Normalize();
GetComponent<Rigidbody>().AddForce(toCenter * 9.8f, ForceMode.Acceleration);
if (AlignToPlanet)
{
Quaternion q = Quaternion.FromToRotation(-transform.up, -toCenter);
q = q * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, q, 1);
}
Debug.Log(CrossPlatformInputManager.GetAxis("Vertical"));
GetComponent<Rigidbody>().AddForce(transform.forward * 2, ForceMode.Impulse);
}
First off, you should avoid calling GetComponent more than necessary. Just call it once to get the Rigidbody in Awake then refer to the result in FixedUpdate.
Second, once you determine the object's up direction, you can use cross products to determine what would be the forward that is closest to the previous forward while still maintaining that up.
Then, you can use Quaternion.LookRotation to set that up and forward.
Finally, you should use Rigidbody.MoveRotation to set the rotation.
Altogether:
private Rigidbody rb;
public Transform planet;
public bool AlignToPlanet;
public float gravityConstant = -9.8f;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Vector3 toCenter = planet.position - transform.position;
toCenter.Normalize();
rb.AddForce(toCenter * 9.8f, ForceMode.Acceleration);
if (AlignToPlanet)
{
Vector3 newUp = -toCenter;
Vector3 newRight = Vector3.Cross(newUp, transform.forward);
Vector3 newForward = Vector3.Cross(newRight, newUp);
Quaternion newRot = Quaternion.LookRotation(newForward, newUp);
rb.MoveRotation(q);
}
Debug.Log(CrossPlatformInputManager.GetAxis("Vertical"));
rb.AddForce(transform.forward * 2, ForceMode.Impulse);
}
I set up a new project with your script, and it works fine for me.
The only things I changed (beside the AddForce on the forward to test it) are :
FromToRotationin which you pass opposite vectors (one to the up, and one to the down)Slerp I removed, it is useless since you pass a value of 1.So, it looks like this :
if (AlignToPlanet)
{
// removed the minus in front of toCenter
Quaternion q = Quaternion.FromToRotation(-transform.up, toCenter);
transform.rotation = q * transform.rotation;
}
EDIT
I agree with @Ruzhim : the LookRotation is a better way to compute your new rotation, since it takes also the forward of your object.
(And for the fact to not use the GetComponent in any Update)