using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovementMouse : MonoBehaviour, IPlayerMovement { // Indicates the maximum distance to the ground [SerializeField] private float groundMaxDistance = 500f; // indicates the name of the layer mask to detect (layer masks are used to identify colliders of interest when casting a ray), we are interested in if the player is clicking the ground // See more: https://docs.unity3d.com/ScriptReference/LayerMask.html [SerializeField] private string groundTargetLayerMask = "Floor"; // The destination Point indicated by mouse click Vector3 destinationPosition = Vector3.zero; private bool isMoving; private float speed; public Vector3 GetMovement(float walkSpeed, float runSpeedMultiplier, float rotateSpeed) { isMoving = false; speed = walkSpeed; //If user is pressing left mouse button, proess movement, otherwise return zero movement if (Input.GetMouseButton(0)) { RaycastHit hit; // Cast a ray and check if the ray hits the ground layer mask collider // Set the destination to the point hit LayerMask layerMask = LayerMask.GetMask(groundTargetLayerMask); if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, groundMaxDistance, layerMask.value)) { destinationPosition = hit.point; } // Get offset to destination position Vector3 deltaTargetPosition = destinationPosition - transform.position; // Calculate short destination (Current position + 2) to move this frame in the direction of the destination position, keeping y the same Vector3 destinationDirection = transform.position + deltaTargetPosition.normalized * 2.0f; // Rotate character in direction of the destination direction // First read and store the original rotation, so you can gradually rotate the character to the new direction using the Quaternion.Slerp method Quaternion originalRotation = transform.rotation; // Rotate the character's transform forward in the direction of the destination ( transform.LookAt(destinationDirection); // Now gradually rotate character in world space from current rotation to new rotation after looking at target transform.rotation = Quaternion.Slerp(originalRotation, transform.rotation, rotateSpeed * Time.deltaTime); isMoving = true; return destinationDirection; } else { return Vector3.zero; } } private void OnAnimatorMove() { // https://docs.unity3d.com/Manual/ScriptingRootMotion.html // Have to manualy update the position because of "in-place" humanoid animations (moving on the spot) if (isMoving) { transform.position = Vector3.MoveTowards(transform.position, destinationPosition, speed * Time.deltaTime); } } }