- Home /
Detect touch location?
I have a sphere in the centre of my application. When a user touches the screen (iphone) I want to know how many degrees away from the centre sphere it is. So for example if the user touched directly to the right of the sphere it would be "90" or if the user touched directly to the left of the sphere it would be "270". I've searched online but I have no idea how to go about doing this. Any ideas?
Edit: Yey! Problem solved. I used the below code combined with this basic touch code I just wrote:
function Update () {
if ( iPhoneInput.touchCount > 0 ){
for(var touch : iPhoneTouch in iPhoneInput.touches) {
Debug.Log(touch.position);
}
}
}
Answer by Noise crime · Jul 11, 2010 at 02:25 PM
There are two ways you could approach this, one is to use Vector3.Angle() to get the angle between one vector and another, or you could use Atan2, which is essentially results in the same thing.
Basically you need to find the vector from the screen origin (center of your sphere in screen co-ordinates) and the current mouse position. With this you can find the angle between it and say a vector pointing straight up (in screen space)
Vector3 ScreenOrigin = new Vector3( Screen.width/2,Screen.height/2,0);
Vector3 MousePos = Input.mousePosition - ScreenOrigin;
Vector3 UpVector = new Vector3(0,1,0);
float angle = Vector3.Angle(UpVector, MousePos);
print("Mouse: " + MousePos + " Screen: " + ScreenOrigin + " Angle: " + angle);
This will give you a value of 0 straight up, 90 directly left/right and 180 straight down. To get it into 0-360 instead of 0-180 on both sides, you'll have work out which side the mouse is on and adjust accordingly. However i'd just use the second method below.
Vector3 ScreenOrigin = new Vector3( Screen.width/2,Screen.height/2,0);
Vector3 MousePos = Input.mousePosition - ScreenOrigin;
float angle = Mathf.Atan2(MousePos.x, MousePos.y) * Mathf.Rad2Deg;
if (angle < 0) angle2 = 360+angle;
print("Mouse: " + MousePos + " Screen: " + ScreenOrigin + " Angle: " + angle );
This should give you 0(and 360) straight up, 90 to the right, 180 down and 270 left.
Ah sorry, a lot of the stuff is right in your above post but I forgot to mention it's for an iPhone application. I've edited my first post. I'm not sure what the iPhone equivalent of mousePosition is. Oh and I was looking at a full 360 degree angle rather than just 90 etc, they were just examples. Thanks for your help anyway, I might try and work from there!
Ah, didn't know things were slightly different for iPhone, glad you found the code for that. As to my code I guess you've discovered that it does do all angles 0 to 360, I was just pointing out the directions of the main 4.
Although If you can hold the iPhone in any orientation then you may have to adjust the Atan(x,y) values to account for that. Same with the UpVector in the first example, where i'm setting it that x is left/right, y is up/down on the screen and z is ignored.