- Home /
Question by
tsx5000 · Jan 24, 2014 at 01:39 PM ·
move an objectclick to move
Transitional Movement to mouse click position
I want to move my object to the position where i click. I searched a lot for a solution and came up with this (attached it to the object that has to be moved):
Vector3 targetPosition;
RaycastHit hit;
void Start ()
{
targetPosition = transform.position;
hit = new RaycastHit();
}
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000.0f))
{
targetPosition = new Vector3(hit.point.x, hit.point.y, hit.point.z);
transform.position = targetPosition;
}
}
//rigidbody.AddForce (0f, 0f, 0.3f, ForceMode.Acceleration);
}
void OnEnterCollision()
{
targetPosition = transform.position;
}
The problem I am facing is that the above code 'teleports' my object to the click location. I need a smooth movement from the current to the target position I tried using Lerp and MoveTowards methods but somehow the object does not move in the y axis.
Also, even though the above code works, the object keeps moving even after reaching the target location. Any Suggestions ?
Comment