- Home /
Zero Gravity like Physics?
Hi, I need to find a way so that once a certain key is pressed, there is no gravity in the space around me. I am creating a 2D game which does not use Unity's built in gravity, instead I have this piece of code in the update function of each of my objects:
if (gravityType == "up") {
rb.AddForce (Camera.main.transform.up * 9.8f);
} else if (gravityType == "down") {
rb.AddForce (Camera.main.transform.up * -9.8f);
} else if (gravityType == "null") {
// ===== What goes here? =====
}
This just means a negative force of 9.8 units per second will be applied on the Y axis to the object it is applied to. I want to find a way how there is no gravity in the scene, so obviously I will have to stop applying this force, so that things seem to bounce of surfaces and maintain there current velocity over longer distances. If anybody knows how to do this it would be much appreciated if you could let me know.
Many Thanks,
Tommy Eaves
Answer by Demonicdaron · Aug 08, 2015 at 11:03 AM
You can simply replace the 9.8f by a variable, and set that variable to zero when the key is held down. So you could change your code to:
if (gravityType == "up") {
myGravity = 9.8f;
} else if (gravityType == "down") {
myGravity = 9.8f;
} else if (gravityType == "null") {
myGravity = 0f;
}
rb.AddForce (Camera.main.transform.up * myGravity);
To do something when a button is held down use
if (Input.GetKey())
To do something when a button is pressed down (only once when is pressed down, the action will not continue as you hold the button down) use
if (Input.GetKeyDown())
Still, I'm not sure that your code will do what I think you want, but this should anwer the question for what you have provided. Hope this helps
Hi, thanks for the help but for some strange reason when I set myGravity to 0f my object continues to fall. I have turned off both 2D and 3D gravity in the scene under Edit/ProjectSettings/Physics and Edit/ProjectSettings/Physics2D. Any ideas how I can fix this problem?
Gravity is acceleration, not speed; therefore if you stop the acceleration, it doesn't mean the the object will stop, as it may have some velocity left. To stop it completely, you can use CharacterController.$$anonymous$$ove(Vector3.zero)
It's working perfectly now you have explained it, thanks.