• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

[SOLVED] Collision box and targeting enemies

G

Grim Xavier

Guest
So I have a problem with the way my turret targets enemies. currently it checks to see if there's an enemy 750 pixels in front of it, and then attacks that enemy. Here's the code:


if collision_rectangle(x, y-96, x-750, y+32, obj_enemyParent, false, true) {
var stoneAttack
stoneAttack = instance_create(x, y-50, obj_stoneAttack) with (stoneAttack) {
direction = point_direction(x, y, obj_enemyParent.x, obj_enemyParent.y)
}

The problem is that if there's an enemy inside the collision box AND an enemy outside of the collision box at the same time, the turret could very well attack the enemy outside of the collision box, no matter where it is. This is because, as the code reads now, if there's an enemy in the collision box, the turret will target ANY enemy. How do I specify to only attack enemies that walk into this collision box? Any ideas would be greatly appreciated.
 
W

whale_cancer

Guest
You just need to look for the specific instance instead of the object. Merely grab the id of the instance in some way. Here is the easiest way given your existent code, but it could be done more efficiently.

Code:
if collision_rectangle(x, y-96, x-750, y+32, obj_enemyParent, false, true) {
enemy_instance = collision_rectangle(x, y-96, x-750, y+32, obj_enemyParent, false, true)
var stoneAttack
stoneAttack = instance_create(x, y-50, obj_stoneAttack) with (stoneAttack) {
direction = point_direction(x, y, enemy_instance.x, enemy_instance.y)
}
Please enclose your code in the code tag for easy readability in the future.
 
W

whale_cancer

Guest
Cool, thanks! Sorry, idk how to code tag things.
No worries. You can just click on the icon to the left of the floppy disk in the rich text editor.

I also just realized you probably need to use the .other construct like this:
Code:
with (stoneAttack) {
direction = point_direction(x, y, other.enemy_instance.x, other.enemy_instance.y)
}
 

TheouAegis

Member
Why are you running collision_rectangle() twice?

LOL ;)

Code:
var enemy=collision_rectangle(x, y-96, x-750, y+32, obj_enemyParent, false, true);
if enemy {
    (instance_create(x,y-50,obj_stoneAttack)).direction = point_direction(x, y-50, enemy.x, enemy.y);
}
 
Last edited:
W

whale_cancer

Guest
Why are you running collision_rectangle() twice?

LOL ;)

Code:
var enemy=collision_rectangle(x, y-96, x-750, y+32, obj_enemyParent, false, true);
if enemy {
    (instance_create(x,y-50,obj_stoneAttack)).direction = point_direction(x, y-50, enemy.x, enemy.y);
}
Here is the easiest way given your existent code, but it could be done more efficiently.
Less typing 4 me :)
 
Top