Skip to content

Instantly share code, notes, and snippets.

@MrCl0wnLab
Last active January 12, 2022 01:08
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 MrCl0wnLab/cf5957affb9a46ec62bdf71d1d7cb546 to your computer and use it in GitHub Desktop.
Save MrCl0wnLab/cf5957affb9a46ec62bdf71d1d7cb546 to your computer and use it in GitHub Desktop.
Controller Unity3D
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
private float _speed;
public float walkSpeed = 2f;
public float runSpeed = 4f;
private Rigidbody _playerRigidbody;
private Vector3 _movimentVector3;
private Animator _playerAnimator;
void Start()
{
_playerRigidbody = GetComponent<Rigidbody>();
_playerAnimator = GetComponent<Animator>();
}
private void Update() {
float _horizontal = Input.GetAxis("Horizontal");
float _vertical = Input.GetAxis("Vertical");
bool _run = Input.GetKey(KeyCode.LeftShift);
_movimentVector3 = new Vector3(_horizontal, 0, _vertical);
print("CheckFire - Fire2: "+CheckFire("Fire2"));
if(_movimentVector3 != new Vector3(0,0,0) && !_run){
_speed = walkSpeed;
if (CheckFire("Fire2")){
_playerAnimator.SetBool("IsAimingWalk",true);
}else{
_playerAnimator.SetBool("IsWalking",true);
}
}else if(_movimentVector3 != new Vector3(0,0,0) && _run){
_speed = runSpeed;
if (CheckFire("Fire2")){
_playerAnimator.SetBool("IsAimingRun",true);
}else{
_playerAnimator.SetBool("IsRunning",true);
}
}else{
_speed = 0;
ResetAnimation();
}
MovimentPlayer();
}
private void ResetAnimation(){
_playerAnimator.SetBool("IsRunning",false);
_playerAnimator.SetBool("IsWalking",false);
_playerAnimator.SetBool("IsAimingWalk",false);
_playerAnimator.SetBool("IsAimingRun",false);
}
private void FixedUpdate()
{
RotacionarPlayer();
}
bool CheckFire(string _fire){
if (Input.GetAxisRaw(_fire) != 0){
return true;
}else{
return false;
}
}
void MovimentPlayer(){
_playerRigidbody.MovePosition(transform.position + _movimentVector3 * _speed * Time.deltaTime);
//transform.rotation = Quaternion.LookRotation(_movimentVector3);
}
void RotacionarPlayer(){
Vector3 _positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
Vector3 _mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
Vector3 _direction = _mouseOnScreen - _positionOnScreen;
float angle = Mathf.Atan2(_direction.y,_direction.x) * Mathf.Rad2Deg -90.0f;
transform.rotation = Quaternion.Euler(new Vector3(0, -angle, 0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment