Object dissapears on MoveTowards
Hi,
I have a project where I want to move my player to the position I click.
I have the object, a camera and a terrain object.
I attached the script to the terain object. When I click my object doesnt move toward the point but dissapears. It still is there but the x, y and z are going all over the place. What am I doing wrong?
public class MouseHandler : MonoBehaviour
{
public GameObject unit;
Vector3 targetPosition;
public float speed;
void Start()
{
targetPosition = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
float step = speed * Time.deltaTime;
unit.transform.position = Vector3.MoveTowards(transform.position, targetPosition, step);
}
}
}
}
Since you set targetPosition
to transform.position
(in the Start
function), the distance between the start position and end position of $$anonymous$$oveTowards
equals to 0 which leads to this behaviour.
What does Debug.Log( Vector3.Distance( transform.position, targetPosition ) )
output just before you set the position of your unit?
Answer by Hellium · Oct 30, 2017 at 09:19 AM
Are you sure you don't want to call :
unit.transform.position = Vector3.MoveTowards(unit.transform.position, targetPosition, step);
Also, I guess you want the unit to be moved towards the position click. If so, put the following line before setting the position :
targetPosition = hit.point;
Now the object doesnt dissapear but now it only slides a fraction of a pixel to the side. If I click a bunch of times you see it moveing slightly
Try to increase the speed, but keep in $$anonymous$$d that $$anonymous$$oveTowards
does not move an object over time like an animation. To do so, you will need coroutines.
I put all the move stuff in a move function now and run it in the update frame. Now the object moves but only to the right. almost there thnx for the tips :)
Found the problem. $$anonymous$$y mouse position isnt being read correctly. its always the same wherever I click.