Code: Select all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PlayerState
{
walk,
attack,
interact,
stagger,
idle
}
public class PlayerMovement : MonoBehaviour {
public PlayerState currentState;
public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;
// Start is called before the first frame update
void Start()
{
currentState = PlayerState.walk;
animator = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
animator.SetFloat("x", 0);
animator.SetFloat("y", -1);
}
// Update is called once per frame
void FixedUpdate()
{
change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal");
change.y = Input.GetAxisRaw("Vertical");
if(Input.GetButtonDown("attack") && currentState != PlayerState.attack && currentState != PlayerState.stagger)
{
StartCoroutine(AttackCo());
}
else if (currentState == PlayerState.walk || currentState == PlayerState.idle)
{
UpDateAnimationAndMove();
}
}
private IEnumerator AttackCo()
{
animator.SetBool("attacking", true);
currentState = PlayerState.attack;
yield return null;
animator.SetBool("attacking", false);
yield return new WaitForSeconds(0.2f);
currentState = PlayerState.walk;
}
void UpDateAnimationAndMove()
{
if (change != Vector3.zero)
{
MoveCharacter();
animator.SetFloat("x", change.x);
animator.SetFloat("y", change.y);
animator.SetBool("moving", true);
}
else
{
animator.SetBool("moving", false);
myRigidbody.velocity = Vector3.zero;
}
void MoveCharacter()
{
change.Normalize();
if (Input.GetKey(KeyCode.LeftShift))
{
/// myRigidbody.MovePosition(transform.position + change * speed * Time.fixedDeltaTime * 1.5f);
myRigidbody.velocity = change.normalized * speed * 1.3f;
}
else
{
/// myRigidbody.MovePosition(transform.position + change * speed * Time.fixedDeltaTime);
myRigidbody.velocity = change.normalized * speed;
}
}
}
public void Knock(float knockTime)
{
StartCoroutine(KnockCo(knockTime));
}
private IEnumerator KnockCo(float knockTime)
{
if (myRigidbody != null)
{
yield return new WaitForSeconds(knockTime);
myRigidbody.velocity = Vector2.zero;
currentState = PlayerState.idle;
myRigidbody.velocity = Vector2.zero;
}
}
private void Update()
{
if (Input.GetKey(KeyCode.W)) //Moves up
{
change += Vector3.up;
}
if (Input.GetKey(KeyCode.A)) //Moves left
{
change += Vector3.left; //Moves down
}
if (Input.GetKey(KeyCode.S))
{
change += Vector3.down;
}
if (Input.GetKey(KeyCode.D)) //Moves right
{
change += Vector3.right;
}
}
}
Thanks ahead of time!