converting a touch to 3d world coordinates

I have this game called Sonic Boom:

https://play.google.com/store/apps/details?id=com.coolfone.sonicboom

When you touch a screenpoint, it tries to move the spaceship to it.

I didn’t use Unity for it, but I’d like to make a Unity version.

Anyone know how to make it so I can take the screen coords of a touch and figure out where in world coordinates the spaceship should try to go?

I suspect I didn’t really do it quite right when I made the current version without Unity.

I’m thinking of having the camera maybe at 0,0,-10.

And maybe the spaceship will start at 0,0,0 and always have a z value of 0.

So, I’m thinking maybe I should have a ray going from the camera through the point in the near clipping plane. Then, somehow I want to see where the ray is when z=0.

Also, I’m looking at this function and wondering if it will work:

However, I am sorely confused about the z value that is being passed in for a screen point.

It makes much more sense to me for the screen point to be an x and y without a z.

I may try to use this one since it seems to make more sense:

It says position.z is ignored, which makes sense to me.

Then somehow I would want to take that Ray and find out where it is when z=0. Anyone know how to do that?

Thanks. Have a blessed day.

I found some code that seems to work:

if (Input.GetMouseButtonDown (0)) {
Debug.Log("mouse button pressed");
Debug.Log("mouse x: " + Input.mousePosition.x);
Debug.Log("mouse y: " + Input.mousePosition.y);
Debug.Log("mouse z: " + Input.mousePosition.z);

Vector3 myVec = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f);

Vector3 v3 = Camera.main.ScreenToWorldPoint(myVec);

Debug.Log("v3.x: " + v3.x + " v3.y " + v3.y + " v3.z " + v3.z);

this.transform.position = v3;
}

Basically, my object is at z=0, and my camera is at 0, 0, -10.

So, I passed in 10 for the z parameter for ScreenToWorldPoint.

I guess that is pretty much the secret sauce… passsing in 10 for z.

This is typically done in one of two ways. ScreenToWorldPoint will give you a point a fixed distance away from the screen.

The other common method is to raycast from the screen until you hit something, and use that point. ScreenPointToRay and Physics.Raycast are your friends here.

1 Like