- Home /
Question by
osdosd · Dec 11, 2021 at 10:36 PM ·
animationscripting problem2d gamebeginnermovement script
How do I stop moving when attacking?
In my 2D game the player can move around fine, but when I press the attack button (space) the attack animation plays but the character doesn't stop moving.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PlayerState
{
walk,
attack,
interact
}
public class PlayerMovement : MonoBehaviour
{
public PlayerState currentState;
public float moveSpeed;
public Rigidbody2D rb;
public Animator anim;
private Vector2 moveDirection;
private Vector2 lastMoveDirection;
void Start()
{
currentState = PlayerState.walk;
}
void Update()
{
ProcessInputs();
}
void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
if((moveX == 0 && moveY == 0) && moveDirection.x != 0 || moveDirection.y != 0)
{
lastMoveDirection = moveDirection;
}
if(Input.GetButtonDown("attack") && currentState != PlayerState.attack)
{
StartCoroutine(AttackCo());
}
else if(currentState == PlayerState.walk)
{
Move();
Animate();
}
moveDirection = new Vector2(moveX, moveY).normalized;
}
void Move()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
void Animate()
{
anim.SetFloat("AnimMoveX", moveDirection.x);
anim.SetFloat("AnimMoveY", moveDirection.y);
anim.SetFloat("AnimMoveMagnitude", moveDirection.magnitude);
anim.SetFloat("AnimLastMoveX", lastMoveDirection.x);
anim.SetFloat("AnimLastMoveY", lastMoveDirection.y);
}
private IEnumerator AttackCo()
{
anim.SetBool("Attacking", true);
currentState = PlayerState.attack;
yield return null;
anim.SetBool("Attacking", false);
yield return new WaitForSeconds(.3f);
currentState = PlayerState.walk;
}
}
Thank you to anyone who has the brains to help! :D
Comment
Answer by lluisvinent4 · Dec 12, 2021 at 02:28 AM
Check if you are attacking before moving.
if(Input.GetButtonDown("attack") && ...)
attack
else if(currentState == PlayerState.walk)
move
else if((moveX == 0 && moveY == 0) && ...)
lastMoveDirection = moveDirection;
The same thing happens: When I attack I can still move the character but the attack animation plays. Thank you for trying to help though!
Try this
if(Input.GetButtonDown("attack") && ...)
attack
else if(currentState == PlayerState.walk && currentState != PlayerState.attack)
move
else if((moveX == 0 && moveY == 0) && ...)
lastMoveDirection = moveDirection;
It still doesn't work. Maybe if it stops the function Move(); in the coroutine? Sorry for causing you this much trouble.