Gravity

I’m trying to alter gravity!

What I have is a collider, and when my character hits that collider, I want gravity to flip. I’ve got this code:

function OnTriggerEnter (other : Collider) {
if (other.name == "altergravity1") {
Physics.gravity = Vector3(0,-1.0,0);
}
}

Now, I’ve tried playing around with those numbers (0,0,1) (1,0,0) etc but nothing seems to happen.

Also, once I get this to work, I only want the change in gravity to affect my character, everything else in the level needs to stay normalised or it’ll destroy a lot of stuff I have setup later in the level!

Any ideas?

Mike

EDIT: Realised some major mistakes in my code. Still doesn’t work though, lol!

First check whether you’re actually getting the collision event. E.g. add print("flipping gravity!"); before flipping it.

Then, your code sets gravity to point downwards (-1 along y axis), which probably does not mean “flipped”. The default value is (0,-9.8,0); you change it to (0,-1,0). Actual “flip” could be just inverting the current gravity:

Physics.gravity = -Physics.gravity;

BUT if you want this on your main character only, then changing global gravity is not good. I suggest leaving the global gravity as it is, turn the gravity OFF for the main character, and instead constantly add some force to simulate the gravity.

It seems I was getting the actual gravity altered, only it wasn’t affecting my character so I didn’t notice it. All my various rocks and props were going flying in the background, lol! Managed to get everything back to normal just about!

I’ll try the simulate gravity and see how that goes. Thanks! :slight_smile:

Mike

Are you using the character controller on your character? If so, then you have to simulate gravity yourself, because character controllers are not affected by physics.

If you’re using some of the scripts that come with Unity or examples, there are good chances it already contains the gravity simulation code; all you need to do is make it support the gravity switch.

Yeah, I’m using a modified version of the Third Person Controller scripts that come with a character controller.

I’m not entirly sure how I’ll get it working as I can’t see any kind of (0,-1,0) type setup anywhere in the script that mentions gravity.

But I’ll have a go! Thanks! :slight_smile:

Mike

Just search for “gravity” in the ThirdPersonController script. It has a couple of variables for gravity, and a function called ApplyGravity() that does all the magic. It is somewhat complex, because there can be so many gravity related things you want to do differently in a character controller.