Change player gravity by pressing a key?
Hi!
I'm trying to create a isometric prototype project, where the gravity of the player object changes with a press of a key.
The problem is, I have nothing more to offer than this question, how should I start, or where should I start to solve this problem myself?
Thanks in advance! :^)
PS. If you're kindhearted, and you're willing to provide me a sample code, please do write it in C#
Answer by Toon_Werawat · May 28, 2016 at 02:36 AM
If you want to chang gravity. These are gravity setting in
Edit > Project settings > Physics
But if you want to change via script. You can do this.
public bool gravitySwitch;
void Update()
{
if (Input.GetKeyDown(Keycode.G) //Detect if player press G key. You can learn more at Unity Input. If you want
{
gravitySwitch = !gravitySwitch;
if (gravitySwitch)
{
Physics.gravity = new Vector3(0,9.81,0); //Invert
}
else If (!gravitySwitch)
{
Physics.gravity = new Vector3(0,-9.81,0); //Default unity
}
}
}
If you want more complex code. For whatever reason. Here
public bool gravitySwitch;
public void Update()
{
if (Input.GetKeyDown(Keycode.G)
{
gravitySwitch = !gravitySwitch;
Physics.gravity = !gravitySwitch ? new Vector3(0,9.81) : new Vector3(0.9.81,0);
}
}
O$$anonymous$$. Here is whole script then.
using UnityEngine;
public class GravitySwitcher : $$anonymous$$onoBehaviour
{
public Vector3[] gravityList = new Vector3[] { };
void Update()
{
if (gravityList.Length < 5) { Debug.Log("gravity List is has to be more or exactly at 5"); return; }
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.G))
{
//Restore
Physics.gravity = gravityList[0];
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.H))
{
Physics.gravity = gravityList[1];
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.J))
{
Physics.gravity = gravityList[2];
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Y))
{
Physics.gravity = gravityList[3];
}
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.U))
{
Physics.gravity = gravityList[4];
}
}
}
Attach this script to any gameobject and then expend gravityList. Change Size to 5. And then adject value in there value you want.
Your answer
Follow this Question
Related Questions
How can I move an object in the direction another object is facing. 1 Answer
Smooth Rotation on WASD keys pressed? 1 Answer
GravityBody hides Rigidbody 1 Answer
Gravity is not working 0 Answers