I’m currently working on a 2D puzzle game, and I wish to change the gravity with the player rotation (z-rotation).
The player object is the parent and the camera is the child. If the z-rotation is free, the camera will rotate with the player.
I have tried with the following code:
{
public float rotate;
void Update () {
rotate = gameObject.transform.eulerAngles.z;
if (rotate >= 45 && rotate < 100) {
Physics.gravity = new Vector3(-20, 0, 0);
}
}
}
I can’t make it work. I have tried with different if statements. If the player reaches a degree between 2 variables the gravity will change, but I do think it is not stable and will have many flaws.
I think this approach is fine. The only thing to watch out for is wrap-around of the rotation values… you might want to add something like “if (rotate < 0) rotate += 360;” right after you get your rotate value (i.e. at line 7).
I have turned the rigibody off and tried to create a “default” gravity when the payer is “flat” on the platform (z is 0 or 360)
I have used following code, but the player keeps floating.
I’m confused. You said you turned the rigidbody off — that means it is no longer hooked into the physics system. So I wouldn’t expect Physics.gravity to have any effect. Do you have some other script that’s doing something with Physics.gravity?
This will spew a line to the console on every frame, which is not something you want to leave in there for long, but when you’re confused, you need a view into what’s happening. This ought to provide it.
Note that this code would change the gravity sideways, and then never change it back. Is that what you’re seeing?
Thank you very much for the great help. I did not know you could use the debug like that! It have helped a lot.
I tried your code and it did turn the character sideways, but if you jump it will rotate the character and it will fly into the infinity and beyond. I do know how to fix it, I just need to add the other gravity functions.