1
\$\begingroup\$

In my (Google Cardboard) Android app I would like to make my camera move on Touch. That movement state should be controlled via a "switch", so when I touch the screen the camera starts to move and when I tap again it stops. To achieve that I appended this script to the camera:

using UnityEngine;
using System.Collections;

public class TapControl : MonoBehaviour {

public float speed;
public int state = 0;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
        state += 1;
    }
    if (state % 2 == 0)
    {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }
    }
}

The state-integer increases every touch. But nonethless, the camera's behavior can be described as a "hold-touch to move" when the state-variable is even.

So, to make it short: Can anyone detect any programming mistakes i made that could cause this strange behavior?

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

Try changing your state integer into a state boolean, as below.

[Edit] I added the block to make sure the touch count is greater than zero. All sample code I read does this.

Also, your speed in your code is zero. Just making sure you initialized it to a value.

using UnityEngine;
using System.Collections;

public class TapControl : MonoBehaviour {

    public float speed;
    public bool isCameraMoving = false;

    // Update is called once per frame
    void Update () {
        if (Input.touchCount > 0) 
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began)
            {
                isCameraMoving = !isCameraMoving; // Toggle moving state
            }
        }

        if (isCameraMoving)
        {
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        } 
    }
}
\$\endgroup\$
  • \$\begingroup\$ Before my seemingly unnecessairily complicated program snipped I posted, I actually had the boolean-solution, but that gave me the same errors. The speed I just defined in the Unity inspector. I will give your idea a try and inform you about the result, but I think that it is a conflict with the scripts that are included and applied to the Google Cardboard-Camera(s) by default. \$\endgroup\$ – hoppla1232 Sep 14 '16 at 17:49

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.