This code is for a simple 2D tile-based game. x1
and y1
are the mouse coordinates in the world. entity->x1
and entity->y1
is the point where the player is, the shot origin.
I would like to know how to keep the current output while simplifying the code and improving performance.
void shoot(Map *map, Entity *entity, int x1, int y1)
{
float slope = (y1 - entity->y1) / (x1 - entity->x1);
float y = entity->y1; //Weapon position
Block *block;
if(x1 > entity->x1){
y += slope;
for(float x = entity->x1 + 1; x < map->width && y < map->height && y > 0; ++x){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y += slope;
}
}
else
if(x1 < entity->x1){
y -= slope;
for(float x = entity->x1 - 1; x > 0 && y < map->height && y > 0; --x){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y -= slope;
}
}
//When the player shoots up or down
else {
slope = (y1 > entity->y1) ? 1 : - 1;
y += slope;
while(y < map->height && y > 0){
//Get block at position x y. Check if found a hit
if((block = map_block_at(map, x1, y))->type != EMPTY){
block_cause_damage(block, entity->hand_item->weapon.damage);
return;
}
y += slope;
}
}
}
The code for Entity
and Map
:
typedef struct Entity {
Renderable renderable;
plist_id render_id;
Point (*get_current_position)(struct Entity *, uint32_t);
int health, attack_damage, running, jumping;
float x0, y0, x1, y1;
uint32_t t0, t1;
enum {LEFT, RIGHT} side;
Image **texture;
Item *hand_item;
Backpack backpack;
} Entity;
typedef struct {
Renderable renderable;
plist_id render_id;
int width, height;
Block *blocks;
Camera *camera;
} Map;