- Home /
Get position of touch
I'm making a 3D game and i need to know whether or not the user taps on the left or right side of the screen. I have the code bellow, its attached to the ball that I'm trying to move. Im developing for a mobile device so i was wondering if theres a better way to use the Touch function instead of Mouse
Answer by NerdClown · Sep 02, 2016 at 08:03 AM
You can get the position of a touch (in pixel coordinates) and then compare it to your screen width. Pretty identical to what you have, actually!
Something along these lines:
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
if (Input.GetTouch(0).position.x > (Screen.width / 2))
{ }
}
Answer by nj4242 · Sep 02, 2016 at 01:46 PM
If you want to use touch controls and unity player both refer this code, This is how I use touch controls for android devices :
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
private float x = 0.0f;
private float y = 0.0f;
public float dragSensitivity = 2; //You can choose whatever sensitivity you like use.
//Pre Processors - To Check if we are running on Editor, Android or iOS.
#if !UNITY_ANDROID && !UNITY_IOS || UNITY_EDITOR
void Update( )
{
//Touch Controls.
if(Input.touchCount == 1)
{
Touch f0 = Input.GetTouch(0); //Detecting touch
Vector3 f0Delta2 = new Vector3(f0.deltaPosition.x, -f0.deltaPosition.y, 0);
x+= Mathf.Deg2Rad*f0Delta2.x* dragSensivity*10;
y+= Mathf.Deg2Rad*f0Delta2.y* dragSensivity*10;
//Use your code
}
if(Input.GetMouseButtonUp(0)
{
//use your code here
}
}
#endif
}
Note here that : This code will help you get how to use the touch controls. I have used this code for camera movements to the left and right. It will help your camera to move along with the GameObject movements.
Get a better idea on how to use touch controls from here : https://unity3d.com/learn/tutorials/projects/2d-roguelike-tutorial/adding-mobile-controls
Your answer
Follow this Question
Related Questions
Is there any way to empty the touch array. 0 Answers
Touch screen move - android 1 Answer
How to instantiate an object by touching 1 Answer
Issue with Touch Buttons 1 Answer
Touchscreen in Unity 1 Answer