- Home /
Question by
Fickum · Mar 22, 2020 at 12:40 PM ·
vector3touch controlsscreentoworldpointmovment
problem with ScreenToWorldPoint (keep getting the same coordinates)
I wrote a code to move my player to the touch position :
public class Movment : MonoBehaviour
{
public Vector2 touch;
public Transform Player;
new Vector3 vec;
// Update is called once per frame
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
touch = Camera.main.ScreenToWorldPoint(Input.touches[i].position);
vec = new Vector3(touch.x, touch.y, 5);
Debug.DrawLine(Vector3.zero, vec, Color.red);
Debug.Log(vec);
Player.position = vec;
}
}
}
it keeps giving me (-3.7, 3.5, 5.0) I spent 2 hours reading solutions and answers (like setting a z coordinate to the vector3) but nothing solved it
Comment
Answer by Namey5 · Mar 23, 2020 at 02:27 AM
You are passing a Vector2 (touch.position) to ScreenToWorldPoint, which takes a Vector3 input. This will end up casting to a Vector3 with an assumed z-coordinate of 0, which means the function will always return the camera's position regardless of the screen point. If you want to find the world space position of a point on screen with a set z-position, you can use a plane-raycast;
//This is the world space z-coord of the points
float zPosition = 5f;
if (Input.touchCount > 0)
{
//Z-Position is irrelevant with ScreenPointToRay
Ray ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
//Create a new plane on the z-axis
Plane plane = new Plane (new Vector3 (0f, 0f, -1f), new Vector3 (0f, 0f, zPosition));
//Raycast against the plane
if (plane.Raycast (ray, out float hit))
{
//Find the world pos of our screen point on the plane
Vector3 hitPos = ray.GetPoint (hit);
Player.position = hitPos;
}
}