Skip to content

Instantly share code, notes, and snippets.

@JonathanYin
Created October 28, 2017 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathanYin/ebc407fba011d468080f9282e5447b21 to your computer and use it in GitHub Desktop.
Save JonathanYin/ebc407fba011d468080f9282e5447b21 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 6f;
Vector3 movement;
Animator anim;
Rigidbody playerRigidbody;
int floorMask;
float camRayLength = 100f;
void Awake()
{
floorMask = LayerMask.GetMask ("Floor");
anim = GetComponent<Animator> ();
playerRigidbody = GetComponent<Rigidbody> ();
}
void FixedUpdate()
{
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
Move (h, v);
Turning ();
Animating (h, v);
}
void Move(float h, float v)
{
movement.Set (h, 0f, v);
movement = movement.normalized * speed * Time.deltaTime;
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit floorHit;
if (Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) {
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation (playerToMouse);
playerRigidbody.MoveRotation (newRotation);
}
}
void Animating(float h, float v)
{
bool walking = h != 0f || v != 0f;
anim.SetBool ("IsWalking", walking);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment