Hello,
I’m trying to move a character to a point hit on the screen. The initial rotation and move works perfectly but once the character reaches the endPoint it keeps moving and rotating around that point.
public class MovePlayer : MonoBehaviour {
//flag to check if the user has tapped / clicked.
//Set to true on click. Reset to false on reaching destination
private bool flag = false;
public float speed;
public CharacterController controller;
Vector3 endPoint;
public Animator animator;
void Start(){
endPoint=transform.position;
}
void Update(){
if(Input.GetMouseButton(0)){
//locate where the player clicked on the terrain
LocatePosition();
}
// Move player
if(flag){
MovetoPosition();
}
}
void LocatePosition(){
RaycastHit hit;
Ray ray;
//for unity editor
#if UNITY_EDITOR
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//for touch device
#elif (UNITY_ANDROID || UNITY_IPHONE || UNITY_WP8)
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
#endif
if(Physics.Raycast(ray,out hit,1000)){
flag = true;
endPoint = new Vector3(hit.point.x,hit.point.y,hit.point.z);
}
}
void MovetoPosition(){
if(flag && !Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude)){
Quaternion newRotation = Quaternion.LookRotation(endPoint-transform.position);
newRotation.x=transform.rotation.x;
newRotation.z=transform.rotation.z;
animator.SetBool("Walk",true);
transform.rotation = Quaternion.Slerp(transform.rotation,newRotation,Time.deltaTime*10);
controller.SimpleMove(Vector3.forward*speed);
}else if(flag && Mathf.Approximately(gameObject.transform.position.magnitude, endPoint.magnitude)) {
flag = false;
animator.SetBool("Walk",false);
}
}
}
I’m using Unity5.