Animating a click to move character
private Vector3 Position;
public float Here;
public float Speed;
public float RotSpeed;
public CharacterController Controller;
//animations
public AnimationClip ModIdle;
public AnimationClip ModRun;
// Use this for initialization
void Start () {
Position = transform.position;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0))
//locate mouse position
LocatePosition ();
//move player to the mouse place
MovePlayer ();
}
void LocatePosition()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 1000)) {
Position = new Vector3(hit.point.x, hit.point.y, hit.point.z);
}
Debug.Log (Position);
}
void MovePlayer()
{
//when the object is moving
if (Vector3.Distance (transform.position, Position) > Here) {
Quaternion NewRotation = Quaternion.LookRotation (Position - transform.position);
NewRotation.x = 0f;
NewRotation.z = 0f;
transform.rotation = Quaternion.Slerp (transform.rotation, NewRotation, Time.deltaTime * RotSpeed);
Controller.SimpleMove (transform.forward * Speed);
GetComponent<Animation>().Play(ModRun.name);
}
else
{
GetComponent<Animation>().Play(ModIdle.name);
Here is my code. As you can see I'm using a Raycast to do my click to move stuff (I'm following an online tutorial) but the movement doesn't seem to trigger animations in the animator, nor do the animations called in the script play either. I'm not sure where I'm going wrong as I've followed the destructions to the letter (except for using as the guide was using an older version of unity).
Should I be using the raycast to rotate my player and then add.velocity rather than just move to position? would that be better?
Sorry and thank you in advanced for any assistance. Nem.
Could you tell me what online tutorial did you use?
Answer by unity_pq4f9m5BG-5Inw · Feb 24, 2020 at 06:35 AM
Hy @nemervore you can follow this video to make click to move, it is simple, short and clean. https://www.youtube.com/embed/DPBdqbP8MFI