-
-
Save reZach/ded0250f3a2f5850470e3ba10636846b to your computer and use it in GitHub Desktop.
Unity click to move and player controls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
using UnityEngine.AI; | |
public class PlayerMove : MonoBehaviour | |
{ | |
CharacterController CharacterController; | |
public Camera CharacterCamera; | |
public float Speed = 6.0f; | |
public float JumpSpeed = 8.0f; | |
public float Gravity = 20.0f; | |
public Vector3 ClickedToWalk; | |
private NavMeshAgent NavMeshAgent; | |
private Vector3 MoveDirection = Vector3.zero; | |
void Start() | |
{ | |
CharacterController = GetComponent<CharacterController>(); | |
NavMeshAgent = GetComponent<NavMeshAgent>(); | |
} | |
void Update() | |
{ | |
if (!NavMeshAgent.isStopped && Vector3.Distance(NavMeshAgent.transform.position, ClickedToWalk) < 0.5f || | |
(Input.GetKeyDown(KeyCode.W) || | |
Input.GetKeyDown(KeyCode.A) || | |
Input.GetKeyDown(KeyCode.S) || | |
Input.GetKeyDown(KeyCode.D))) | |
{ | |
// Stop auto-navigation | |
NavMeshAgent.isStopped = true; | |
} | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
Ray ray = CharacterCamera.ScreenPointToRay(Input.mousePosition); | |
RaycastHit hit; | |
if (Physics.Raycast(ray, out hit, 100.0f)) | |
{ | |
if (hit.transform.gameObject.layer == LayerMask.NameToLayer("Walkable")) | |
{ | |
ClickedToWalk = hit.point; | |
NavMeshAgent.isStopped = false; | |
NavMeshAgent.SetDestination(hit.point); | |
} | |
else | |
{ | |
NavMeshAgent.isStopped = false; | |
} | |
} | |
} | |
if (NavMeshAgent.isStopped) | |
{ | |
// Calculate move direction directly from axes | |
MoveDirection = Quaternion.Euler(0, CharacterCamera.transform.eulerAngles.y, 0) * new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); | |
if (MoveDirection != Vector3.zero) | |
{ | |
print("c"); | |
MoveDirection *= Speed; | |
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below | |
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied | |
// as an acceleration (ms^-2) | |
MoveDirection.y -= Gravity * Time.deltaTime; | |
// Move the controller | |
CharacterController.Move(MoveDirection * Time.deltaTime); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment