Multiple hotboxes are activated
I am a beginner to Unity and have many questions! In my game when I move at a diagonal angle it activates multiple hit boxes. How do I stop this?
Theres no enough information to help you on this... can you post some images, a goal or some context?
I have a 2d top down game. I can move around and attack just fine; when I'm moving left the left attack animation plays when I attack. But, I have a system when I attack, say, I'm facing up, the up hit box is activated and then deactivated when I stop moving. But the problem is that when I move at an angle, all of the hotboxes become active.
Below is an image of what happens:
this seems like a coding problem... can you post you character controller?
Answer by osdosd · Dec 16, 2021 at 10:49 PM
Sure! Here it is:
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;
// anim = GetComponent<Animator>();
// rb = GetComponent<Rigidbody2D>();
}
void Update()
{
ProcessInputs();
}
void ProcessInputs()
{
// Gets directional input
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
// Sets the lastMoveDirection to moveDirection when movement stops
if((moveX == 0 && moveY == 0) && moveDirection.x != 0 || moveDirection.y != 0)
{
lastMoveDirection = moveDirection;
}
// Checks if the "attack" button is pressed (space) and starts the coroutine if so
if(Input.GetButtonDown("attack") && currentState != PlayerState.attack)
{
StartCoroutine(AttackCo());
}
// Moves and animates the character if the currentState is walking
else if(currentState == PlayerState.walk)
{
Move();
Animate();
}
// Sets "isMoving" to be True or False
if(moveX != 0 || moveY != 0)
{
anim.SetBool("isMoving", true);
}
else
{
anim.SetBool("isMoving", false);
}
moveDirection = new Vector2(moveX, moveY).normalized;
}
// Move
void Move()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
// Animate
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);
}
// Attack Coroutine
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;
}
}