Skip to content

Instantly share code, notes, and snippets.

@Trainfire
Last active September 24, 2016 19:23
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 Trainfire/2af0d8193d09b393e4c3873459fcc3db to your computer and use it in GitHub Desktop.
Save Trainfire/2af0d8193d09b393e4c3873459fcc3db to your computer and use it in GitHub Desktop.
using UnityEngine;
class PlayerController : MonoBehaviour
{
public float _moveDistance;
public float _raycastDistance;
public void LateUpdate()
{
if (Input.GetKeyUp(KeyCode.A))
AttemptMove(Vector3.left);
if (Input.GetKeyUp(KeyCode.S))
AttemptMove(Vector3.back);
if (Input.GetKeyUp(KeyCode.D))
AttemptMove(Vector3.right);
if (Input.GetKeyUp(KeyCode.W))
AttemptMove(Vector3.forward);
}
void AttemptMove(Vector3 direction)
{
// Check if there's something in the specified direction.
if (CanMove(direction))
{
Move(direction);
}
else
{
Debug.LogWarning("We cannae move!");
}
}
void Move(Vector3 direction)
{
// Immediately move to the next position.
transform.position += direction * _moveDistance;
}
bool CanMove(Vector3 direction)
{
RaycastHit hit;
Physics.Raycast(transform.position, direction, out hit, _raycastDistance);
Debug.Log(hit.collider);
return hit.collider == null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment