Move an object up while touch is active

| | August 10, 2015

I’m trying to move an object towards the top of the screen while the touch is active.
This is my current code. When I am touching the screen, the object I’m trying to move just keeps it’s place (and the gravity seems to be disabled from this point). I’d be glad if someone could help me in this case. Thanks in advance!

public class PlayerScript : MonoBehaviour
{

public Vector2 jumpForce = new Vector2(0, 12);
public int speed = 3;

void Update()
{
    for (int i = 0; i < Input.touchCount; i++) {
                    Touch touch = Input.GetTouch (i);
                    while(touch.phase == TouchPhase.Began) {
                            // Touch are screens location. Convert to world
                                rigidbody2D.velocity = new Vector2(0, speed);
                                rigidbody2D.AddForce(jumpForce);
                    } 

            }
     }
 }

One Response to “Move an object up while touch is active”

  1. The code you’ve posted is only checking for touches that began on this frame. If all you want is to verify that any touch is present, you can just check if Input.touchCount is greater than zero.

Leave a Reply