1

WHAT I TRY? A script that notice when a button is pressed and while it's pressed it should make a object move to the left.

WHAT'S THE PROBLEM? No matter where I touch the screen, the Rididbody moves. But i want the body just moving when the Button is pressed.

I know there must be a posibility to make it work with INPUT.GetButton("ButtonName") but i didnt get it working. Thanks for help!

    public class LeftTouch : MonoBehaviour {

        public Rigidbody rb;
        public float leftForce = 120;
        bool pressed = false;


        // Update is called once per frame
        void Update () {

                //Is there a touch?
                if (Input.touchCount > 0)
                {                    

                    if (Input.GetTouch(0).phase == TouchPhase.Began)
                    {
                        //TOUCH START
                        pressed = true;

                    }

                    if (Input.GetTouch(0).phase == TouchPhase.Ended)
                    {
                        //TOUCH END
                        pressed = false;                   

                    }
                }

                if (pressed == true)
                {
                  //Make ridigbody move to left
                    rb.AddForce(-leftForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
                }

        }
    }
  • Create a function that moves the object. Your `if(pressed == true)` condition seems to achieve this. And add that function to UI Button's on click property. – Thalthanas Feb 05 '18 at 06:21
  • But with onClick property I cant tell that I only should work when the button is pressed down. Is it not possible to add code to the script to just activate the AddForce when the Touch Input is inside the Button? Maybe with Input.GetButton("ButtonName") ? –  Feb 05 '18 at 06:25
  • 1
    You need to use`OnPointerDown` and `OnPointerUp` for this with a boolean variable you set to `true` and `false` in each function respectively. You can then check that boolean variable in the `Update` function. – Programmer Feb 05 '18 at 06:57
  • Did OnPointerDown and OnPointerUp also work for Touching Buttons on Android? –  Feb 05 '18 at 07:07
  • Yes. It works on mobile and desktop. – Programmer Feb 05 '18 at 07:45

0 Answers0