- Home /
How do you change gravity with a press of a button? Unity 2D
I want my player to be able to change gravity when I press the space bar... kinda like in this game http://www.worigame.com/gravity-shift-puzzle-game.html
Is there any code I can use.... and any other tips so that my game can be as similar as that one.
Sorry it the question is kind of confusing, english is not my first language
Answer by Eno-Khaon · Nov 11, 2015 at 02:31 AM
For this, Physics2D.gravity is your friend.
To give an example of a simple implementation to start from, you could try something like this:
// C#
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Physics2D.gravity *= -1;
}
}
With this bit implemented into a script, gravity will reverse by pressing spacebar (by multiplying by -1).
And if you want to change the gravity on your character only you can change it on its rigidbody component by code.
void Update()
{
if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
{
GetComponent<RigidBody2D>().gravityScale *= -1;
}
}
I think this should be gravityScale not gravity.
Ah yes correct! I forgot to double check on the documentation. I have edited my message accordingly.
Answer by Monagui · Nov 11, 2015 at 01:23 PM
Thanks! I ended up doing using this code in case anyone needs it, thanks again :D
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
Physics2D.gravity *= -1;
}
}
}
Your answer
Follow this Question
Related Questions
Issues after updating to Unity 5 1 Answer
How to check if a enemy is moving up or down? 1 Answer
Virtual Joystick jump in unity2d 0 Answers
How do i prevent the player from dragging a ui element off screen? 1 Answer
How to connect a object to a moving player without messing its movement up 2 Answers