1
\$\begingroup\$

I have a sphere with a rigidbody on it, and it moves to the right continously as I need it, but as it moves I want the space bar to be able to switch the gravity (so it either rides on the ceiling or on the floor), as it moves along to the right.

Please help, have been googling consistently for the past 3 hours.

Here is the code I have so far:

public class movement : MonoBehaviour {

    public float movementSpeed = 10;
    private bool haspressed;

    void Start()
    {
    }

    void FixedUpdate()
    {

        transform.Translate(Vector3.down * movementSpeed * Time.deltaTime);

        if (Input.GetKeyDown ("space") && haspressed == true) {
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime);
            haspressed = false;
        } else if (Input.GetKeyDown ("space") && haspressed == false) {
            transform.Translate (Vector3.right * movementSpeed * Time.deltaTime);
            haspressed = true;
        }
    }
}

Thank you sooo much!

\$\endgroup\$
1
\$\begingroup\$

Figured it out.Now just need to figure out how to use only one key for this action.

using UnityEngine;

using System.Collections;

public class gravity : MonoBehaviour {

public float ychange = 5;
void Update () {
{
    if(Input.GetKey ("space")){

        Physics.gravity = new Vector3(0f,ychange,0f);}

}
    if (Input.GetKey (KeyCode.UpArrow)) {
        Physics.gravity = new Vector3(0f,-ychange,0f);}
    }
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Have you considered using a bool variable to track your script's isGravityInverted state? Then you can toggle that state when GetKeyDown returns true. \$\endgroup\$ – DMGregory Jan 5 '17 at 22:12
  • \$\begingroup\$ Ended up just putting each key press in its own method so I could also call it to a button click and handle touch input in IOS, it worked great. \$\endgroup\$ – Mike noah Jan 18 '17 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.