- Home /
How to disable player gravity
My script makes it that whenever you enter an area of gravity (a collider) you enter the gravity of the planet.
What I want is when you leave, you can be in zero gravity, but what the code is doing is when you leave the planet, you continue to be affected by the planet's gravity. I want a way to set the players gravity off when you leave the planet.
This must be because gravity areas become the player's parent whenever it enters another gravity area. Well I'm really stuck here
public class GravityOrbit : MonoBehaviour
{
public float Gravity;
// Start is called before the first frame update
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<GravityCtrl>())
{
other.GetComponent<GravityCtrl>().Gravity = this.GetComponent<GravityOrbit>();
}
else
{
}
}
private void OnTriggerExit(Collider other)
{
}
// Update is called once per frame
void Update()
{
}
}
Gravity
public class GravityCtrl : MonoBehaviour
{
public GravityOrbit Gravity;
public Rigidbody Rb;
public float RotationSpeed = 20;
void Start()
{
Rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (Gravity)
{
Rb.transform.parent = Gravity.transform;
Vector3 gravityUp = Vector3.zero;
gravityUp = (transform.position - Gravity.transform.position).normalized;
Vector3 localUp = transform.up;
Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * transform.rotation;
Rb.GetComponent<Rigidbody>().rotation = targetRotation;
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, RotationSpeed * Time.deltaTime);
Rb.GetComponent<Rigidbody>().AddForce((-gravityUp * Gravity.Gravity) * Rb.mass);
}
else
{
}
}
}
Answer by Tibllec · Mar 11 at 05:05 PM
Oh god, what a day, ok, the only thing i had to do was set the OnTriggerExit in the gravityCtrl code, and in it put Gravity = null;
Answer by aqeel25 · Mar 11 at 04:30 AM
private void OnTriggerEnter(Collider other)
{
other.transform.GetComponent<Rigidbody>().useGravity = false;
}
private void OnTriggerExit(Collider other)
{
other.transform.GetComponent<Rigidbody>().useGravity =true;
}
Hi @aqeel25 , sorry for the misunderstanding.
I want a way to turn off players gravity when you leave the planet.
The code you used uses unity gravity, but I had to use a different gravity because of the hyspheric world
Ok, then try reparenting it in statement where it exits collision. I hope this will work. Give it try
Hey! I managed at the beginning of the game for the player to be off the planet, and only start to be affected by gravity when entering its collider. (now the player is no longer a child of gavity forever)
But I found that if the player is affected by gravity once, gravity continues to affect him even if he leaves the collider.