This the script 'Click to Move', but now i don't understand one thing...
Why the object (capsule in this case), when i start the project, it move automatically in te position x:0 - y:0 - z:0? The capsule have other coordinates initially...
var obj:Transform;
var hit:RaycastHit;
var move: boolean = false;
private var startTime:float;
var speed = 1;
function Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 10000))
{
move = true;
startTime = Time.time;
}
}
if(move)
{
obj.transform.position = Vector3.Lerp(obj.transform.position, hit.point, Time.deltaTime * speed);
if(obj.transform.position == hit.point)
{
move = false;
}
}
}
One problem is that you're using the same RaycastHit variable for both moving the object and for raycasting - so if the raycast fails after the first click, you're going to be moving your object to somewhere crazy
Another issue is that move is public, so it could be set to true without the raycast
Try something like this instead:
var obj:Transform;
private var hitPoint : Vector3;
private var move: boolean = false;
private var startTime:float;
var speed = 1;
function Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
var hit : RaycastHit; // no point storing this really
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 10000))
{
hitPoint = hit.point;
move = true;
startTime = Time.time;
}
}
if(move)
{
obj.position = Vector3.Lerp(obj.position, hitPoint, Time.deltaTime * speed);
if(obj.position == hitPoint)
{
move = false;
}
}
}
It worked fine for me. You did have one too few close brackets (}) in the code above, so that may be effecting your results. I think your issue is elsewhere...
Though I did get rid of the obj: Transform; and just used the transform of the object I put the script on. If you are looking to move multiple units at once, you might consider a boolean "isSelected" type variable. Then if the unit is not selected, it will ignore any destination. Then you just pass the coordinates to all of the units that are (i.e separating your Raycasting from your moving)...