Last active
March 13, 2023 22:43
-
-
Save feranmii/7c36f3b57106105122a658da0b5c593b to your computer and use it in GitHub Desktop.
Simple Top Down Controller
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 System.Collections; | |
using System.Collections.Generic; | |
using MoreMountains.Feedbacks; | |
using UnityEngine; | |
[RequireComponent(typeof(Rigidbody))] | |
public class PlayerMovement : MonoBehaviour | |
{ | |
private float hor; | |
private float vert; | |
public float movementSpeed = 2f; | |
private Rigidbody _rigidbody; | |
private Vector3 movementVector; | |
[Header("Smoothing")] | |
public float rotationSpeed; | |
public bool isMoving; | |
private bool disabled; | |
private void Awake() | |
{ | |
_rigidbody = GetComponent<Rigidbody>(); | |
} | |
private void Update() | |
{ | |
if(disabled) | |
return; | |
hor = Input.GetAxis("Horizontal"); | |
vert = Input.GetAxis("Vertical"); | |
isMoving = movementVector.magnitude > .01f; | |
movementVector = new Vector3(hor, 0, vert).normalized; | |
Move(); | |
HandleRotation(); | |
} | |
private void HandleRotation() | |
{ | |
if(!isMoving) | |
return; | |
var lookRot = Quaternion.LookRotation(movementVector); | |
var rot = Quaternion.Slerp(transform.rotation, lookRot, rotationSpeed); | |
transform.rotation = rot; | |
} | |
void Move() | |
{ | |
_rigidbody.AddForce(movementSpeed * Time.deltaTime * movementVector); | |
} | |
public void DisableMovement() | |
{ | |
_rigidbody.velocity = Vector3.zero; | |
_rigidbody.isKinematic = true; | |
disabled = true; | |
} | |
public void EnableMovement() | |
{ | |
_rigidbody.isKinematic = false; | |
disabled = false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment