'Converting mouse (touch) position with ScreenToWorldPoint doesn't work
I googled as much as I could, but no solution.
Aim: change touch coordinates from pixels (screen left-bottom corner x0) to game coordinates in a 3D environment, although I don't need the Z position, because the camera is not moving, and I just need to track the X position and with the current state my clicks (touches) are always at positive X.
Code:
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
touchPos.z = 3;
if (touch.phase == TouchPhase.Stationary)
{
if (touch.position.x < 0)
turnSpeed = 8f;
else if (touch.position.x > 0)
turnSpeed = -8f;
}
if (touch.phase == TouchPhase.Ended)
{
turnSpeed = 0f;
}
}
}
Camera position: x: 0.027 y: 3.847 z: -2.238. I've tried setting touchPos.z = from -3 to 10., but no luck.
Solution 1:[1]
Thanks to shingo, here's the solution:
Change
If (touch.position.x < 0)toif (touchPos.x < 0);Set the Z value before or when calling ScreenToWorldPoint. I went with:
Vector3 touchPos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0.3f));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
