Make an object go towards an object

R

Retnuh

Guest
I'm trying to get a projectile object to go towards my player object. can't figure out how to do it.
please and thanks.

(not sure if i'm posting this in the right place, i'm new here)
 
  • Thinking
Reactions: Mut
W

wagyu_so_gud

Guest
for the projectile code:

Code:
direction = point_direction(x,y,obj_player.x,obj_player.y);
keep in mind if you put the point_direction in the step event, it will act like a 'homing missile' that continuously moves in the direction of the player. However, if you use this at the create event, it will set the direction (once) at that specific time.
 
B

Becon

Guest
move_towards_point( player_obj.x, player_obj.y, 4 );
Try that. 4 is the speed it moves toward that point.
 

Nocturne

Friendly Tyrant
Forum Staff
Admin
I feel that I should point out that while the above code is correct, it will give you problems later... Why? Because noone has explained the dangers of using the "point" method to access an instance position or properties... basically doing:

Code:
obj_player.x
will cause a crash in your game if the instance being checked doesn't exist so you should wrap the check in an "instance_exists" call, like this:

Code:
// CREATE EVENT OF BULLET
if instance_exists(obj_player)
{
move_towards_point( player_obj.x, player_obj.y, 4 );
}
else instance_destroy();
Note that there is also an "else" there that will destroy the bullet instance instantly if there is no instance of the target object in the room (in this case obj_player).

That said, personally I think there is a far better way to do this involving the instance that is doing the shooting rather than the bullet. Basically, you check for the instance in the shooter object and only create an instance if the target exists, and in the shooter object you set the direction and speed etc...

This solution looks a bit like this:

Code:
// STEP EVENT OF THE SHOOTER (Enemy?)
if instance_exists(obj_Player)
{
var dir = point_direction(x, y, obj_player.x, obj_player.y);
with (instance_create(x, y, obj_Bullet))
    {
    speed = 4;
    direction = dir;
    }
}
So, now if there is no instance of the player, the object just won't shoot, and if there is, it will shoot AND set the direction and speed of the bullet object. :)
 
B

Becon

Guest
Ahh yes....the old lack of if instance_exists crash. Nocturne is totally right on that one. =o)
 
Top