Skip to main content
3 of 15
added 150 characters in body

Transforming attack range to match player facing in one of 8 directions

I am making a little top-down 2D RPG right now and I'm struggling with the range of my attacks. I use OverlapBoxAll to identify the enemies in range, which works fine when facing right. It's just that when I move to the left, the range doesn't extend from the left of my player, but just stays on the right.

I want to make a script that makes the range transform, based on where you are facing (I'm using 8 directional movement). I'm just not experienced enough to know how. I also just made this script while following along a tutorial by blackthornprod. Its name was was melee combat. He just doesnt show how to change it.

Here is the PlayerAttack script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAttack : MonoBehaviour{
    
    private float timeBtwAttack;
    public float startTimeBtwAttack;

    public Transform attackPos;
    public LayerMask whatIsEnemies;
    //public Animator camAnim;
    //public Animator playerAnim;
    public float attackRangeX;
    public float attackRangeY;
    public int damage;

    void Update(){
        
        if(timeBtwAttack <= 0){

            if(Input.GetKey(KeyCode.Mouse0)){
                //camAnim.SetTrigger("shake");
                //playerAnim.SetTrigger("attack");
                Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX, attackRangeY), 0, whatIsEnemies);
                for (int i = 0; i < enemiesToDamage.Length; i++) {
                    enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
                }
            }
        timeBtwAttack = startTimeBtwAttack;
    } else  {          
        timeBtwAttack -= Time.deltaTime;   
    }
}
        void OnDrawGizmosSelected(){
            
            Gizmos.color = Color.black;
            Gizmos.DrawWireCube(attackPos.position, new Vector3(attackRangeX, attackRangeY, 1));

    }
}