- Home /
Is there a possible way to make gravity change when the character collides with something?
I would like the gravity to change when the character collides with an empty object.
Answer by Suddoha · Oct 03, 2015 at 02:27 AM
Yes, you have access to the gravity via the Physics class. If the "empty object" is supposed to be an area rather than a certain point in space, you should at least have a collider set to isTrigger that you can run into, so that you can use the OnTriggerEnter(Collider other) or a normal collider so that you can use OnCollisionEnter(Collision other) and execute the actions you want to happen.
Changing the gravity is just one line of code (of course you'll probably have more logic going on, but that's how to change it):
3D:
Physics.gravity = new Vector3(x,y,z);
2D:
Physics2D.gravity = new Vector2(x,y);
Basic example using trigger:
void OnTriggerEnter(Collider other)
{
// do some stuff
if(other.CompareTag("theTagForObjectsThatChangeGravity"))
Physics.gravity = new Vector3(x,y,z);
}
with x,y,z being the desired values for the new gravity.
I'm still not able to do it. I changed the ideia and i would like the object to be a sprite, ins$$anonymous$$d of an empty object. I would like to, when the player pass through the sprite, add a certain ammount of gravity . In the case, i would like to work with OnTriggerEnter.How can i do it? I'm having trouble in this part!
If you're working with 3D, you would use:
// C#
void OnTriggerEnter(Collider other)
{
}
whereas in 2D, you would use:
// C#
void OnTriggerEnter2D(Collider2D other)
{
}
The documentation (linked for each version) describes the requirements for their usage. To quote the 3D implementation, "Trigger events are only sent if one of the colliders also has a rigidbody attached." -- So make sure at least one object has a Collider with trigger enabled and the other has at least a Rigidbody.
I did it! Thanks! But i have a final question. What would be the lines of code so i can put other events to happen, besides that?