Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class PlayerBehaviour : MonoBehaviour
- {
- // Variable set for calculation in update
- // Max speed, in units per second, that the character moves.
- float speed = 9;
- // Acceleration while grounded
- float walkAcceleration = 75;
- // Deceleration applied when character is grounded and not attempting to move
- float groundDeceleration = 70;
- // Max height the character will jump regardless of gravity
- float jumpHeight = 7;
- // Main Unity Physics ref
- private Vector2 velocity;
- private Rigidbody2D rb;
- // Additional ref
- private BoxCollider2D boxCollider;
- // State for checking
- public enum State
- {
- Ground = 0,
- Jump = 1,
- Fall = 2,
- }
- private State state = State.Ground;
- private void Start()
- {
- rb = GetComponent<Rigidbody2D>();
- }
- // Update is called once per frame
- void Update()
- {
- float moveInput = Input.GetAxisRaw("Horizontal");
- velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, walkAcceleration * Time.deltaTime);
- transform.Translate(velocity * Time.deltaTime);
- if (moveInput != 0)
- {
- velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, walkAcceleration * Time.deltaTime);
- }
- else
- {
- velocity.x = Mathf.MoveTowards(velocity.x, 0, groundDeceleration * Time.deltaTime);
- }
- Vector2 ve = rb.velocity;
- if (state == State.Ground && Input.GetButtonDown("Jump"))
- {
- ve.y = jumpHeight;
- }
- ve.x = 0;
- rb.velocity = ve;
- }
- void FixedUpdate()
- {
- //CameraWork goes here if nessary
- }
- void OnCollisionEnter2D(Collision2D collision)
- {
- if (collision.gameObject.tag == "Platform")
- {
- state = State.Ground;
- velocity.y = 0;
- }
- }
- void OnCollisionExit2D(Collision2D collision)
- {
- if (collision.gameObject.tag == "Platform")
- {
- if (state == State.Ground)
- {
- state = State.Fall;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement