Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerMovement : MonoBehaviour
- {
- private Rigidbody2D rb;
- private SpriteRenderer sprite;
- private Animator anim;
- private float dirX = 0f;
- [SerializeField] private float moveSpeed = 4f;
- private bool isPunching = false;
- private bool isCrouching = false;
- // Start is called before the first frame update
- private void Start()
- {
- rb = GetComponent<Rigidbody2D>();
- sprite = GetComponent<SpriteRenderer>();
- anim = GetComponent<Animator>();
- }
- // Update is called once per frame
- private void Update()
- {
- // If currently punching or crouching, disable movement
- if (isPunching || isCrouching)
- {
- dirX = 0f;
- }
- else
- {
- // Allow Movement
- dirX = Input.GetAxisRaw("Horizontal");
- }
- rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
- UpdateAnimationState();
- // Punch on spacebar press
- if (Input.GetKeyDown(KeyCode.Space) && !isCrouching)
- {
- Punch();
- }
- // Crouch on "S" key down
- if (Input.GetKeyDown(KeyCode.S) && !isPunching)
- {
- Crouch();
- }
- // Stand up on "S" key up
- else if (Input.GetKeyUp(KeyCode.S))
- {
- StandUp();
- }
- }
- // Updates animations for player movement
- private void UpdateAnimationState()
- {
- if (dirX != 0f)
- {
- anim.SetBool("walking", true);
- sprite.flipX = dirX < 0f;
- }
- else
- {
- anim.SetBool("walking", false);
- }
- }
- private void Punch()
- {
- if (!isCrouching)
- {
- isPunching = true;
- anim.SetTrigger("punch");
- }
- }
- private void Crouch()
- {
- if (!isPunching)
- {
- isCrouching = true;
- anim.SetBool("crouch", true);
- }
- }
- private void StandUp()
- {
- isCrouching = false;
- anim.SetBool("crouch", false);
- }
- // Called from animation event to signal the end of punch animation
- public void FinishPunch()
- {
- isPunching = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement