- Home /
Object position resets to Camera Position using touch
I am working in adding touch inputs to a game. What i want to do for now is move an object to where I tap in screen space, however whenever I tap the screen, the object I want to move always moves the position of the camera.
touchCount = 0;
foreach (Touch touch in Input.touches)
{
if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
{
touchCount++;
screenTouchPosition = touch.position;
}
if (touchCount == 1)
{
Vector3 objWorldPosition = Camera.main.WorldToScreenPoint(this.transform.position);
objWorldPosition = screenTouchPosition;
this.transform.position = Camera.main.ViewportToWorldPoint(objWorldPosition);
}
}
I know i need to convert the object's world position to screen space but I can't think of what else i need to do.
Answer by Goest_ · Sep 28, 2018 at 04:28 PM
If you want to place an GameObject where you tap on the screen, you're going to have to do convert the screen point to a world point. You will need to use the ScreenToWorldPoint()
method.
Vector3 screenPosition = new Vector3(touch.position.x, touch.position.y, -Camera.main.transform.position.z);
transform.position = Camera.main.ScreenToWorldPoint(screenPosition);
The Vector you give ScreenToWorldPoint() needs to have a z value that represents the distance between the camera and point where you want your vector. -Camera.main.transform.position.z
works if the transform you want to move is 0 on the z axis.