Last active
May 3, 2020 12:19
-
-
Save BanksySan/020906a494848a70c1b146aa2b9a15c9 to your computer and use it in GitHub Desktop.
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; | |
[RequireComponent(typeof(Rigidbody2D))] | |
public class PlayerController : MonoBehaviour | |
{ | |
private const float WALK_SPEED = 2; | |
private const float JUMP_FORCE = 250; | |
private Vector2 _jumpVector; | |
private bool _queueJump; | |
private bool _queueWalkLeft; | |
private bool _queueWalkRight; | |
private Rigidbody2D _rigidbody; | |
private void Start() | |
{ | |
_rigidbody = GetComponent<Rigidbody2D>(); | |
_jumpVector = new Vector2(0, JUMP_FORCE); | |
} | |
private void Update() | |
{ | |
if (Input.GetKeyDown(KeyCode.UpArrow)) _queueJump = true; | |
if (Input.GetKey(KeyCode.LeftArrow)) _queueWalkLeft = true; | |
if (Input.GetKey(KeyCode.RightArrow)) _queueWalkRight = true; | |
} | |
private void FixedUpdate() | |
{ | |
var velocity = _rigidbody.velocity; | |
if (_queueJump) _rigidbody.AddForce(_jumpVector); | |
if (_queueWalkLeft == _queueWalkRight) | |
{ | |
velocity = new Vector2(0, _rigidbody.velocity.y); | |
} | |
else | |
{ | |
if (_queueWalkRight) velocity = new Vector2(WALK_SPEED, _rigidbody.velocity.y); | |
if (_queueWalkLeft) velocity = new Vector2(-WALK_SPEED, _rigidbody.velocity.y); | |
} | |
_rigidbody.velocity = velocity; | |
_queueJump = false; | |
_queueWalkLeft = false; | |
_queueWalkRight = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment