ScreenToWorldPoint

Hi all,

What i’m tryng to do it’s for a strategy game.
I have a map(a plane), and the camera is fixed at a distance to that plane.
With the mousewheel i can zoom in/out on that map.
I detect the click at each unit, and then i click anywhere on the plane.
I want the unit to move to that plane.

To detect where in the plane i clicked, i’m using the ScreenToWorldPoint function, however this is not working as it should.
The third parameter of this function is the distance from the camera to a plane(far clip plane ?)

I tried using the distance from the camera to the map plane, like this :

var p = theCamera.ScreenToWorldPoint(Vector3(mouseX,mouseY,theCamera.position.y));

But i can’t get this to work.

What am i doing wrong ?

thanks,
Bruno

When describing problems, the above isn’t quite sufficient.

The third parameter, as described in the docs, is the distance into the scene along the camera’s z. If as you say, your camera is a fixed distance above the ground then you need to calculate how far away the camera’s y is from the ground’s y. Subtract, then use that as your Z distance.

You can use debug.print and debug.drawline to figure out where the point returned by your function actually is.

You may have better luck casting a ray from your screen point in order to determine what/where you’re clicking. Search the docs for ‘ScreenPointToRay’ or ‘physics.raycast’.

Where is “theCamera” coming from? If you are getting it from Camera.current then you should know that it sometimes (always?) returns the Scene view camera in the editor rather than the one that’s actually in your game, which will no doubt cause problems.

If that’s the case, try using

theCamera = GameObject.Find("Main Camera").camera;

Instead (of course, change Main Camera to whatever you’ve called it).

Or Camera.main, which grabs whatever Camera object has the “main camera” tag set on it.

If you’re trying to simply move your unit to where you clicked on the plane I would cast a ray (with your plane as the layer mask) and then run a coroutine using some method of moving your object. If you’re using character controllers then you would want to use SimpleMove(), otherwise you could run a simple Lerp.