Last active
June 17, 2018 18:16
-
-
Save augustoerico/b37081f524edbbb46b3ef1325e5362b8 to your computer and use it in GitHub Desktop.
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 UnityEngine; | |
public class PlayerMovement : MonoBehaviour { | |
public Camera playerCamera = null; | |
public Animator animator = null; | |
public float moveSpeed = 5.0f; | |
public float crouchedMoveSpeed = 2.5f; | |
public float rotationSpeed = 5.0f; | |
private bool crouched = false; | |
private float speedZ = 0.0f; | |
void Update () { | |
float moveH = Input.GetAxis ("Horizontal"); | |
float moveV = Input.GetAxis ("Vertical"); | |
bool toggleCrouch = Input.GetButtonDown ("Toggle crouch"); | |
Move (moveH, moveV, toggleCrouch); | |
Animate (); | |
} | |
private void Move (float moveH, float moveV, bool toggleCrouch) { | |
if (toggleCrouch) { | |
crouched = !crouched; | |
} | |
float speed = crouched ? crouchedMoveSpeed : moveSpeed; | |
Vector3 movement = new Vector3 (moveH, 0.0f, moveV).normalized; | |
transform.rotation = Rotation (movement); | |
speedZ = movement.magnitude; | |
transform.Translate (new Vector3 (0, 0, speedZ * speed * Time.deltaTime)); | |
} | |
private Quaternion Rotation (Vector3 movement) { | |
Vector3 lookAt = movement.z > 0.8f ? | |
new Vector3 (playerCamera.transform.forward.x, 0, playerCamera.transform.forward.z) : | |
Vector3.zero; | |
Vector3 forward = Vector3.RotateTowards (transform.forward, lookAt + movement, rotationSpeed * Time.deltaTime, 0.0f); | |
return Quaternion.LookRotation (forward); | |
} | |
private void Animate () { | |
animator.SetFloat ("Vertical", speedZ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment