Check if enemy is in range of attack

I have a character that has a slash attack in a 2d top down rpg. It probably covers -45 to 45 degrees in the direction the character is facing. I need some advice on how to determine if an enemy is in that area. I assume it will contain Phaser.Math.Angle.Between and Phaser.Math.Distance.Between? I think.if I could determine if any enemy is within say 20px of the character in any direction then I could check the angle. I hope that is clear…

Yes, you are on the right track! Here’s a suggested approach using Phaser’s Math functions to determine if an enemy is within your character’s slash attack range and angle.

  1. First, calculate the distance between your character and each enemy using Phaser.Math.Distance.Between.

  2. Check if the distance is within 20px. If the distance is less than or equal to 20px, the enemy is within range.

  3. Next, calculate the angle between your character and each enemy using Phaser.Math.Angle.Between.

  4. Check if the angle is within -45 to 45 degrees in the direction your character is facing. You can do this by comparing the calculated angle with the direction your character is facing.

Here’s a sample code snippet to give you an idea:

// Assuming player and enemies are Phaser.Sprite objects
let player = this.player;
let enemies = this.enemies.getChildren();

enemies.forEach(enemy => {
  let distance = Phaser.Math.Distance.Between(player.x, player.y, enemy.x, enemy.y);

  if (distance <= 20) {
    let angle = Phaser.Math.Angle.Between(player.x, player.y, enemy.x, enemy.y);

    if (angle >= player.angle - 45 && angle <= player.angle + 45) {
      // Enemy is within slash attack range and angle
      // Perform slash attack on the enemy
    }
  }
});

You can adjust the range and angle values as needed to fine-tune your character’s slash attack mechanics. I hope this helps! Let me know if you have any further questions.

Please note that this was an AI generated answer

Phaser.Math.Angle.Between() is in radians but player.angle is in degrees. :slight_smile:

1 Like

This is a great starting point, thank you. And I’ll be sure to use the same units when doing the math.

Is there not a way to see if an area contains an object as opposed to checking every object to see if it is in the area? It’s a smallish rpg but seems that checking all enemies may be alot of overhead. And some enemies may not be a part of the enemies group. Maybe they should be?

@samme Good point, I may have missed that.

I never found a way to create the logic of a sword without using an overlap function

1 Like

Oh man! I was overthinking it. Sword slash overlap then check angle and possibly distance, duh. Thank you.

1 Like