简体   繁体   中英

Cannot get TouchPhase to work in Unity3D

Here is my code

using UnityEngine;
using System.Collections;

public class cube : MonoBehaviour {

    bool start;
    // Use this for initialization
    void Start () {
        start = false;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetTouch(0).phase == TouchPhase.Began) {
            start = true;
        }
        if (Input.GetTouch(0).phase == TouchPhase.Ended) {
            start = false;
        }

        if (start) {
            transform.RotateAround (Vector3.zero, Vector3.left, 1);
        }
        else
            transform.RotateAround (Vector3.zero, Vector3.right, 1);
    }
}

When the screen is touched, the start variable should get set to true and the cube should start rotating clockwise and when you let go of the screen it should start rotating anticlockwise but it only rotates clockwise when the screen is begin touched and stops rotating when I let go.

Also another thing, when I set the variable to true by touching the screen, the cube should keep on rotating since the start variable is now true, but it stops as soon as I stop touching the screen. It works with keyboard buttons but not the touchscreen.

if (Input.GetTouch(0).phase == TouchPhase.Began) {
    start = true;
if (start) {
    transform.RotateAround (Vector3.zero, Vector3.left, 1);
}

I have spent hours on this and still cant get my head around where the problem is.

Your code here:

if (Input.GetTouch(0).phase == TouchPhase.Began) {
    start = true;
}
if (Input.GetTouch(0).phase == TouchPhase.Ended) {
    start = false;
}

What will happen if there's no touch on screen? Yes, you'll get an error because the game is trying to access something that isn't there. It will be printed on console if you simulate it on Unity, but as you're using your own device, you'll not be notified of the error that happened.
Add touchCount to your code:

if (Input.touchCount > 0) {
    if (Input.GetTouch (0).phase == TouchPhase.Began) {
        start = true;
    }
    if (Input.GetTouch (0).phase == TouchPhase.Ended) {
        start = false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM