Files
DougDiggem/Assets/PlayerController.cs
T

73 lines
2.1 KiB
C#

using UnityEngine;
public class PlayerController : MonoBehaviour
{
public GameObject DougBody;
public float walkSpeed;
Interactable nearestInteractable;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
RotatePlayerTowardMouse();
Walk();
TryInteract();
}
void Walk()
{
transform.position += DougBody.transform.forward * Input.GetAxis("Vertical") * walkSpeed * Time.deltaTime;
transform.position += DougBody.transform.right * Input.GetAxis("Horizontal") * walkSpeed * Time.deltaTime;
}
void RotatePlayerTowardMouse()
{
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(DougBody.transform.position);
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
float angle = Mathf.Atan2(positionOnScreen.y - mouseOnScreen.y, positionOnScreen.x - mouseOnScreen.x) * Mathf.Rad2Deg;
DougBody.transform.rotation = Quaternion.Euler(new Vector3(0f, -(angle + 90), 0f));
}
void TryInteract()
{
if (Input.GetKeyDown(KeyCode.E) && nearestInteractable != null)
{
nearestInteractable.Interact();
}
}
private void OnTriggerEnter(Collider other)
{
Interactable interactable = other.GetComponent<Interactable>();
// store nearest interactable if it exists
if (interactable != null)
{
nearestInteractable = interactable;
interactable.MoveInsideRange();
}
}
private void OnTriggerExit(Collider other)
{
// just null out interactables when we leave an interactable trigger (we cant and shouldn't overlap interactables)
Interactable interactable = other.GetComponent<Interactable>();
// store nearest interactable if it exists
if (interactable != null)
{
nearestInteractable.MoveOutsideRange();
nearestInteractable = null;
}
}
}