Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- //Components
- private Rigidbody2D rb;
- private Animator animator;
- private SpriteRenderer spriteRenderer;
- private float horizontalAxis;
- [SerializeField]
- private float moveSpeed;
- [SerializeField]
- private float jumpForce;
- [SerializeField]
- private int jumpCount;
- [SerializeField]
- private int maxJumpCount;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- void Start()
- {
- //Get components
- rb = GetComponent<Rigidbody2D>();
- animator = GetComponent<Animator>();
- spriteRenderer = GetComponent<SpriteRenderer>();
- //Default values
- jumpCount = 0;
- }
- // Update is called once per frame
- void Update()
- {
- ControlsUpdate();
- }
- private void FixedUpdate()
- {
- ControlsFixedUpdate();
- }
- private void ControlsUpdate()
- {
- //Get horizontal axis (horizontal movement direction) (-1 if A is pressed, 0 when nothing is pressed, 1 when D is pressed
- horizontalAxis = Input.GetAxis("Horizontal");
- //If player is moving
- if (horizontalAxis != 0)
- {
- //Enable running animation
- animator.SetBool("isRunning", true);
- //Flip sprite
- if (horizontalAxis > 0 && !spriteRenderer.flipX)
- spriteRenderer.flipX = true;
- else if (horizontalAxis < 0 && spriteRenderer.flipX)
- spriteRenderer.flipX = false;
- }
- //If player is not moving, disable running animation
- else
- animator.SetBool("isRunning", false);
- //If player can jump
- if (jumpCount < maxJumpCount)
- {
- //Check if jump keys are pressed
- if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.Space))
- {
- //Modify liniear velocity (Y axis)
- rb.linearVelocityY = jumpForce;
- //For older versions of Unity
- //rb.velocity = new Vector2(rb.velocity.x,jumpForce);
- //Increase jumpCount by 1
- jumpCount++;
- //Enable jumping animation
- animator.SetInteger("jumpCount", jumpCount);
- }
- }
- }
- private void ControlsFixedUpdate()
- {
- rb.linearVelocityX = moveSpeed * horizontalAxis;
- //For old Unity
- //rb.velocity = new Vector2(moveSpeed * horizontalAxis, rb.velocity.y)
- }
- private void OnCollisionEnter2D(Collision2D collision)
- {
- //Reset jump count on collision with platforms
- if (collision.collider.CompareTag("Platform"))
- {
- jumpCount = 0;
- animator.SetInteger("jumpCount", jumpCount);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement