I'm creating a game where the enemies spawn randomly on a map then move towards the player every frame at a random speed. The map has no obstacles so the enemies should always move in a straight line. I wrote the movement function a few times but no matter what the enemies always hit 0, 45, 90, 135, 180, 225, 270, 315 angles but never a straight line. Here is an example of the code:
base_speed = random();
diff_x = abs(enemy_y_pos - player_x_pos);
diff_y = abs(enemy_x_pos - player_y_pos);
if (diff_x > diff_y) {
y_speed = base_speed;
} else if (diff_y > diff_x) {
x_speed = base_speed;
}
if (enemy_x_pos < player_x_pos) {
velocity.x = x_speed;
} else if (enemy_x_pos > player_x_pos) {
velocity.x = -x_speed;
} else {
velocity.x = 0;
}
if (enemy_y_pos < player_y_pos) {
velocity.y = y_speed;
} else if (enemy_y_pos > player_y_pos) {
velocity.y = -y_speed;
} else {
velocity.y = 0;
}
enemy_x_pos = enemy_x_pos + velocity.x;
enemy_y_pos = enemy_y_pos + velocity.y;
This is my first attempt at game programming. I guessing it's should use algorithm like Bresenham’s Line( http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) but my attempts to implement have the same issue. How do I make enemies move in a straight line?