2

I have to work in Game Maker for this project and I want to move a object towards another object. This is what I have got so far. Does anyone know what I am doing wrong? The enemy is now spinning around the player.

draw_sprite(sprite_index,image_index,x,y);
moveSpeed = 1;
angle = arctan2(enemy_obj.x - player_obj.x, enemy_obj.y - player_obj.y);
enemy_obj.x += cos(angle) * moveSpeed;
enemy_obj.y -= sin(angle) * moveSpeed;
anonymous-dev
  • 2,897
  • 9
  • 48
  • 112

1 Answers1

4

Use builtin GM-functions (this code must be placed in the end step event of the enemy object):

angle = point_direction(x, y, player_obj.x, player_obj.y);
x += lengthdir_x(moveSpeed, angle);
y += lengthdir_y(moveSpeed, angle);

or:

direction = point_direction(x, y, player_obj.x, player_obj.y);
if point_distance(x, y, player_obj.x, player_obj.y) > 10 // min distance
{
    speed = moveSpeed;
}

Or you can use motion planning functions, like mp_potential_step or mp_grid_... for A*.

P.S. When you use code like this

angle = arctan2(enemy_obj.x - player_obj.x, enemy_obj.y - player_obj.y);

you must understand that if are several instances of enemy_obj then will be taken only very first of them (with the smallest id)

Dmi7ry
  • 1,777
  • 1
  • 13
  • 25
  • Why does this code have to go in the end_step event instead of just the step event? – Mark Hetherington Jan 23 '15 at 04:48
  • Because all instances changes positions after the `step` event and before the `end step` event. For example, if your object `obj_player` have speed 4 and position x=0 then `x = obj_player.x` for the `step` event will be 0, but for the `step end` event will be 4. So if I do `direction = point_direction(x, y, player_obj.x, player_obj.y)` in the `step` event it will use old `player_obj` position and you will see a some delay. – Dmi7ry Jan 23 '15 at 08:25