Hello, I’ve just started scripting in unity and I’m a total noob. I need my cube follow a finger but not going up on y axis, that’s all. Always follow a finger, but my version of code isn’t working. My cube always going back to the start position. I searched for the info in internet, but after 2 hours of searching didn’t find anything. All I found is Camera.main.ScreenToWorldPoint and I thought that the cube always returns to the start position because my touch is considered on the start screen and I should make it “WorldPoint” but nope, that didn’t work. Help… Please.
void Update()
{
if (Input.touchCount > 0)
{
Vector3 touch = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
if (Input.GetTouch(0).phase == TouchPhase.Stationary || Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.x, 0, touch.z));
transform.position = touchPosition;
}
}
}
}
qobion
2
You are converting screen point to world 2 times. Remove first
Vector3 touch = Input.GetTouch(0).position;
The touch.z needs to be the distance away from the camera that you want your object. If your camera is aligned/facing along the z axis. Get the z distance:
float zDistance = cube.transform.position.z - camera.transform.position.z;
Then:
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.x, 0, zDistance));
transform.position = touchPosition;