# Movement / aiming algorithm in 2d / tiled based game

I'm trying to create simple 2D / tiled base game in JavaScript. Entities are able to move by any number of pixels, but only in one direction at once (can't go in diagonal way). AI for enemies is simple 'zombie movement' (if you see target - go to him).

Currently I've got problem with my shooting mechanism. In my code I've got statement which say something like this:

if (distance_to_target <= weapon_range) {
shoot_in_current_direction();
}


As you can see on example below my problem exist when target is in range in diagonal way. Red rectangle is 'shooter', blue rectangle is 'target', black dots are 'bullets' and black arc line is a weapon range.

My question is: how to implement restrictions which allow to shoot only if target is in good direction, but not exactly on that same x/y coordinate (allow for some margin)? Should I implement more intelligent movement algorithm (i.e A*)?

To be clear... I'm not looking for ready code but rather for some algorithm help.

In order to implement a simple algorithm to do the shooting only in the horizontal or vertical, you can use your player's and the enemy's bounding boxes and their width and height in order to check whether the enemy is "aligned to" the player's bounding box.

Basically, you need to check in all 4 directions whether the enemy's bounding box is within the region cast by the player bounding box's extended edges.

By using this image as a reference, you'd need to check whether the region defined by the t and b points is inside any of the regions defined by the black lines.

In order to do that, you can check (assuming T=(Tx, Ty), B=(Bx, By), t=(tx, ty) and b=(bx, by)):

if player_in_range and (ty > Ty and ty < By) or (by > Ty and by < By) or (tx > Tx and tx < Bx) or (bx > Tx and bx < Bx) then
enemy is inside player's horizontal or vertical reach


Of course, you can make these horizontal and vertical regions more limited if you want by adding a threshold (margin) value to the comparisons above.