You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
RatAttack2D/Assets/Scripts/PlayerMovement.cs

123 lines
3.2 KiB

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private Transform Gr;
private Animator Ani;
private Inputs Input;
private InputAction Walk;
private InputAction Jump;
private InputAction Dash;
private ParticleSystem Fart;
private float x;
private int usedash;
[NonSerialized]public float speedBoost = 1;
public LayerMask g;
public Vector2 dashvec;
public float drag;
public int dashes;
public float Speed;
public float JumpPwr;
private void Awake()
{
Input = new Inputs();
rb = this.gameObject.GetComponent<Rigidbody2D>();
Gr = this.transform.Find("GroundCheck").transform;
Ani = this.gameObject.GetComponent<Animator>();
Fart = this.transform.Find("Fart").GetComponent<ParticleSystem>();
}
private void OnEnable()
{
Walk = Input.Movement.wasd;
Jump = Input.Movement.Jump;
Dash = Input.Movement.Dash;
Walk.Enable();
Jump.Enable();
Dash.Enable();
}
private void OnDisable()
{
Walk.Disable();
Jump.Disable();
Dash.Disable();
}
private void Update()
{
Jump.performed += _ => jump();
Dash.performed += _ => dash();
Vector2 Force = Walk.ReadValue<Vector2>();
rb.velocity = new Vector2(x + Force.x * Speed * speedBoost, rb.velocity.y);
if (Force.x < 0)
{
if (x > 0)
{
x = -x;
}
Ani.SetBool("Running", true);
rb.transform.rotation = new Quaternion(0, 180, 0, 0);
}
else if (Force.x > 0)
{
if (x < 0)
{
x = -x;
}
Ani.SetBool("Running", true);
rb.transform.rotation = new Quaternion(0, 0, 0, 0);
}
else
{
Ani.SetBool("Running", false);
}
if (rb.velocity.y < 0 && !IsGrounded())
{
Ani.SetBool("Falling", true);
}
else
{
Ani.SetBool("Falling", false);
}
if (IsGrounded())
{
if (x > -0.01 && x < 0.01)
{
x = 0;
}
else
{
x = Mathf.Lerp(x, 0, Time.deltaTime * drag);
}
Ani.SetBool("Dash", false);
usedash = dashes;
}
}
private bool IsGrounded()
{
return Physics2D.OverlapBox(Gr.position, new Vector2(6, 1), 0f, g);
}
private void jump()
{
if (IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, JumpPwr);
Ani.SetBool("Jump", true);
}
}
private void dash()
{
if (!IsGrounded() && !Fart.isPlaying && usedash != 0)
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y + dashvec.y);
x += dashvec.x;
Fart.Play();
Ani.SetBool("Dash", true);
Ani.SetBool("Jump", false);
usedash--;
}
}
}