- Home /
Click To Move (should be an easy one)
I thought I'd get my hands dirty with some Unity Javascript but I seem to be falling at the first hurdle. I blatantly and unashamedly took this code from these very forums but need some help getting it to run.
I get an Object ref not set to object error around these lines: var ray = Camera.main.ScreenPointToRay (Input.mousePosition); if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000, layerMask)) but can't for the life of me figure it out. I've attached this code to a character placeholder (couple of bricks) with the hopes of having my 3rd person click to move.
private var move : boolean = false;
function Update () { if (Input.GetButtonDown ("Mouse Left")) { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000, layerMask)) { move = true ; } }
if(move)
{
var wantedPosition= Vector3(hit.point.x, hit.point.y, hit.point.z);
transform.LookAt(wantedPosition);
transform.position = Vector3.Lerp(transform.position, hit.point, Time.time/200);
if(Vector3.Distance(transform.position, wantedPosition) < 0.01)
{
move = false;
}
}
}
Any clues?
Answer by Eric5h5 · Aug 09, 2010 at 03:57 PM
Camera.main needs a camera tagged "MainCamera" in order to find anything.
And where should this $$anonymous$$ainCamera tagged camera be in relation to my Player Placeholder?
Answer by Badger · Aug 09, 2010 at 08:21 PM
I got it to work with the following adjustments:
also, you need an object where you click the mouse, so it can get a position off. Terrain won't do apparently...
private var move : boolean = false; var hit : RaycastHit;
function Update () { if (Input.GetButtonDown ("Fire1")) { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); if(Physics.Raycast(Camera.main.transform.position, ray.direction, hit, 1000)) { move = true ; } }
if(move) { var wantedPosition= Vector3(hit.point.x, hit.point.y, hit.point.z); transform.LookAt(wantedPosition); transform.position = Vector3.Lerp(transform.position, hit.point, Time.time/200);
if(Vector3.Distance(transform.position, wantedPosition) < 0.01)
{
move = false;
}
}
}
If this answered your question, please mark it as the accepted answer.
Your information got me the furthest I've gotten so far, so thank you very much.
(particularly the bit about it not working on the terrain which baffles me).
Your answer

Follow this Question
Related Questions
Click to move around obstacles 2 Answers
Click to Move 2 Answers
Character Controller moves forever after colliding with object 1 Answer
Click to move a character in a terrain 1 Answer
How to move to specific point with character controller 1 Answer