- Home /
How to set and objects gravity direction to Z -10 based on the objects rotation? (2D)
Recently I have been working on a 2D mind-fuzzle game, which more or less turns everything inside out with interesting and intuitive ideas, I can tell you now, if you get motion sickness you won't like this game :P
Anyway, I have been playing around, and I would like the controls of the game to be simple, move the character left and right, and change the characters gravity by pressing space to a vector of (0, -10, 0) or something like that. I have been using (0, -1, 0) for debug purposes.
This vector, however, needs to be based on the players rotation. If I where to move my player of the side of a roof, it would start to rotate half way off the side of the roof, pressing space would then change the players gravity to (0, -10, 0) based on the players rotation, not the static coords.
Here is a picture to explain what I want to do. The left shows the player rotated with the gravity (0, -10, 0) as a vector from the players position, rotation is not considered. The right shows what I want, the gravity as (0, -10, 0) based on the players position AND rotation.
Could someone please help me do this? If I have not been clear enough please ask me, I have made a decent effort to try and get this working :S
Thanks in advance,
~Joe
Answer by robertbu · Mar 01, 2014 at 10:33 PM
Untested but try this:
Physics2D.gravity = -transform.up * gravityAmount;
This will have to be set when your character is rotated. I don't know the nature of your game, but it will effect all the objects in the scene.
@robertbu, I am sure the custom gravity would work, but I would prefer to use the built in gravity.
I hate to contradict but I think you can modify the built-in gravity. If I used this line of code:
Physics2D.gravity = Vector3(0, 10, 0);
Every time I pressed space, I would be able to "invert" gravity. It works fine for me, but I want this Vector to be based around the players rotation.
@ducsuus - Don't hesitate to correct me, and you are right. I'll edit my answer. I based my answer on what was exposed in the Inspector and did not take the time to read the reference.
Your answer

Follow this Question
Related Questions
Unable to set Rotation 1 Answer
Converting www.text or string to rotation or position 2 Answers
Calculating a new position based on where another object is facing 1 Answer
Add an offset to the position of an object in front of it 1 Answer
How can I identify a non-uniform scaled mesh, and fix it? 1 Answer