I’m trying to implement a touch function into my game which lets the player object move to the left or to the right (2D game) depending on the x position the user touches on the screen.
So for example, if the user presses for a long time on the left side of the screen (-x coordinate) the player object moves to the left.
I have the following code in C# but it doesn’t respond to my touches:
using UnityEngine;
using System.Collections;
public class Touch : MonoBehaviour {
public GameObject player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Stationary)
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
//Check if it is left or right?
if(touchDeltaPosition.x < 0.0f){
player.transform.Translate(Vector3.left * 10 * Time.deltaTime);
} else if (touchDeltaPosition.x > 0.0f) {
player.transform.Translate(Vector3.right * 10 * Time.deltaTime);
}
}
}
}
Just in case someone is wondering how I managed to fix this. I used the following code.
This code is not optimized but it shows you how to get started:
using UnityEngine;
using System.Collections;
public class Touch : MonoBehaviour {
public GameObject player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Stationary)
{
Vector2 touchPosition = Input.GetTouch(0).position;
double halfScreen = Screen.width / 2.0;
//Check if it is left or right?
if(touchPosition.x < halfScreen){
player.transform.Translate(Vector3.left * 5 * Time.deltaTime);
} else if (touchPosition.x > halfScreen) {
player.transform.Translate(Vector3.right * 5 * Time.deltaTime);
}
}
}
}