Last active
May 8, 2021 04:00
-
-
Save shivaduke28/25218ce13b8a039ba41761564efaa3e0 to your computer and use it in GitHub Desktop.
SimpleThirdPersonController
This file contains hidden or 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 PlayerController : MonoBehaviour | |
{ | |
[SerializeField] private float maxSpeed = 7f; // meter per second | |
[SerializeField] private float acceleration = 20f; | |
[SerializeField] private float maxRotation = 600f; // degree | |
[Space] | |
[SerializeField] private Vector3 velocity; | |
[SerializeField] private Vector3 move; | |
[Space] | |
[SerializeField] private Camera playerCamera; | |
// new input system | |
private MyControls input; | |
private MyControls.PlayerActions player; | |
private new Rigidbody rigidbody; | |
void Awake() | |
{ | |
input = new MyControls(); | |
player = input.Player; | |
} | |
void Start() | |
{ | |
rigidbody = GetComponent<Rigidbody>(); | |
if (playerCamera is null) | |
{ | |
playerCamera = FindObjectOfType<Camera>(); | |
} | |
input.Enable(); | |
} | |
void Update() | |
{ | |
var value = player.Move.ReadValue<Vector2>(); | |
move = playerCamera.transform.TransformDirection(new Vector3(value.x, 0, value.y)); | |
velocity = Vector3.MoveTowards(velocity, move * maxSpeed, acceleration * Time.deltaTime); | |
} | |
void FixedUpdate() | |
{ | |
// if use rigidbody: | |
rigidbody.velocity = velocity; | |
// else if change transform position directory: | |
// transform.position += new velocity * Time.delaTime; | |
var dir = transform.InverseTransformDirection(move); | |
var r = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg; | |
r = Mathf.MoveTowards(0, r, maxRotation * Time.deltaTime); | |
transform.Rotate(0, r, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment