- Home /
my script not working to move plane to mouse position
I wrote a script and put it into my plane followed by defining myCamera to my main camera. The code runs but nothing happen and my plane just stuck at the middle of my screen. everything seems right but it's not working.
#pragma strict
var myCamera : Camera;
function Start ()
{
}
function Update ()
{
var vec : Vector3 = myCamera.ScreenToWorldPoint(Input.mousePosition);
vec.z = 0.0;
transform.position = vec;
}
Answer by robertbu · Aug 24, 2013 at 03:56 AM
The problem is that the 'z' component of the Vector3 passed to ScreenToWorldPoint() must be the distance in front of the camera. Assuming the standard setup of the camera looking towards positive 'z' try:
vec = Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - myCamera.transform.position.z);
vec = myCamera.ScreenToWorldPoint(vec);
Thanks for the reply but it seems my plane is just stuck in the middle and not responding to the code either.
I did
function Update () { var vec : Vector3; vec = Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - myCamera.transform.position.z); vec = myCamera.ScreenToWorldPoint(vec); }
attached it to my plane.
You have to set the transform.position of the game object, not just do the calculation.
transform.postion = vec;
So the whole function could be:
function Update () {
var = Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z - myCamera.transform.position.z);
transform.position = myCamera.ScreenToWorldPoint(vec);
}