Why is my object moving diagonally upwards and to the right instead of teleporting to touch position & how to make sure object teleports inside the screen and not outside the screen bounds ?

On TouchEnded, I wish my object to jump to the last position of the touch on the screen. On every TouchEnded, it jumps diagonally upwards and to the right for every touch that ends, and does not teleport to where the touch was. Also, how do I keep it from teleporting outside the screen, as after a few touches, it eventually moves outside the screen bounds. Here is my current code :

public Camera camera;

void Update(){

if(Input.touchCount >0) {
		Touch touch = Input.GetTouch (0);
		if (Input.GetTouch(0).phase == TouchPhase.Ended) {
			Vector3 touchpos = Input.GetTouch(0).position;

			Vector3 createPos;
			createPos.x = Input.GetTouch(0).position.x;     
			createPos.y = Input.GetTouch(0).position.y;  
			createPos.z = 0;


TouchPos is going to be in screen coordinates, not world coordinates.

You can convert screen coordinates to world coordinates but you lose the Z which is important.

In order to do an exact match, you have to first transform the object’s current position from world to screen coords, then replace the x and y in that point, then transform back.


Vector3 myObjectPos = Camera.main.WorldToScreenPoint(myObject.transform.position);
myObjectPos.X = touchPoint.X;
myObjectPos.Y = touchPoint.Y;
myObjectPos = Camera.main.ScreenToWorldPoint(myObjectPos);
myObject.transform.position = myObjectPos;

Your problem is line 15


normalized will change the parameters in the vector to 1 if they are greater than 1, -1 if they are less than negative one and 0 if they are between 1 and -1.

CreatePos will always be equal to Vector3(1,1,0)

plus those coordinates on GetTouch(0).position are screen coordinates no world coordinates. so your object wouldn’t even go to the right place if you got rid of normalized

you object would however go to the right place is you got rid of the .normalized if your camera was orthographic.

if your camera is perspective, well, i asked that question a while back. I ended up using plane.raycast, where you raycast a ray from your point.

heres the link to my question, although it was a bit more specific than yours, so it may not apply to you

Managed to figure it out with some help from Reddit. Here is the code

	if(Input.touchCount >0) {
			Touch touch = Input.GetTouch (0);
			if (Input.GetTouch(0).phase == TouchPhase.Ended) {
				Vector3 inputPos = Input.GetTouch(0).position; 
				inputPos.z = 0;
				Vector3 worldPos = Camera.main.ScreenToWorldPoint(inputPos);
				worldPos.z = 0f;
				transform.position = worldPos;