Search Unity

Movement on touch

Discussion in 'Scripting' started by zja203, Aug 19, 2017.

  1. zja203

    zja203

    Joined:
    Sep 18, 2016
    Posts:
    2
    I'm working on a google cardboard VR game. Unlike other cardboard viewers with the magnet slide thing, my viewer (I believe it is a Homido Grab) has a button that extends a small stylus onto the screen. But despite reading a bunch of tutorials I can't find a method to just "touch screen, go forward" I'm not interested in dragging or anything since it's a VR thing so there can't be dragging.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour {
    6.     public Rigidbody rb;
    7.     public float speed;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.         rb = GetComponent<Rigidbody> ();
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.         if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
    17.                 rb.AddForce (transform.forward * speed);
    18.             }
    19.         else if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended){
    20.                 rb.velocity = Vector3.zero;
    21.             }
    22.         }
    23.     }
    24.  
    So to recap, what I want the code to do is make me go in the direction I'm looking when I hold down the button on the headset (which just touches the screen) At the moment the code seems to do nothing. I set up the Google VR demo on my phone and the button worked just fine for that, but the code was too complex form me to understand.
     
  2. Scabbage

    Scabbage

    Joined:
    Dec 11, 2014
    Posts:
    268
    Change line 16 to:
    Code (CSharp):
    1. if (Input.touchCount > 0) {
    It checks if the touch just started, so it'll only add a force for one frame. You can remove the touch phase check from the next branch and just make it an else statement.