Working on a Click to Move script that moves the player object towards the mouse position while the mouse button is held down. My issue right now is that whenever the object collides with something, it’ll just start rotating slowly in a circle, even after the mouse button is released. I even added a line after the “while” loop to reset the transform’s rotation if the button is released, but this doesn’t seem to have any effect at all. Hope someone can help!
I’ve added a quick video illustrating my issue:
var moveSpeed : int;
function Update ()
{
if (Input.GetMouseButtonDown(1))
{
Move ();
}
}
function Move ()
{
while (Input.GetMouseButton(1))
{
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
var mask : int = (1 << 8);
var walkDistance : float = 4.0;
if(Physics.Raycast (ray, hit, Mathf.Infinity, mask))
{
//Rotate the body
var targetRotation = Quaternion.LookRotation(hit.point - transform.position);
var targetRotationY : float = targetRotation.eulerAngles.y;
var facingDirection : float = Mathf.LerpAngle(transform.eulerAngles.y, targetRotationY, Time.deltaTime * 3);
transform.eulerAngles = Vector3(0, facingDirection, 0);
//Check distance from the body towards the mouse position
Debug.DrawRay(transform.position, hit.point, Color.red);
var targetDistance = Vector3.Distance(transform.position, hit.point);
if(targetDistance > 1.2)
{
if(targetDistance > walkDistance)
{
moveSpeed = 6;
} else {
moveSpeed = 2;
}
//Move the body
transform.position += (hit.point - transform.position).normalized * moveSpeed * Time.deltaTime;
}
}
yield;
}
transform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
}