Reputation: 651
I have a character object and a slime object. The character can move and the slime uses the code below to move to the player.
(player_obj is the character)
phy_position_x += sign(player_obj.x - x) * 0.2;
phy_position_y += sign(player_obj.y - y) * 0.2;
How do i make it so the slime doesn't move to the character at all distances? How do I set a radius where the slime starts moving to the character?
Is there an if statement that goes like:
if slime_obj.x < 20 to player.obj.x and slime_obj.y < 20 to player_obj.y {}
Upvotes: 1
Views: 3669
Reputation: 201
To do this is fairly simple, you just to calculate the distance using the distance formula. You can use the point_distance
function in GML. It would look something like this:
if (point_distance(x, y, obj_player.x, obj_player.y) < r) {
//Move towards the player
}
Where 'r' is the radius of the circle you want the enemy to follow the player in.
For more information, you can see here: http://docs.yoyogames.com/source/dadiospice/002_reference/maths/vector%20functions/point_distance.html
Though, this is fairly expensive to calculate (for the CPU) because it uses the square root function. Though the remedy to this is fairly simple. You would make the following script (I named it point_distance_squared, but you can name it whatever you want):
///point_distance_squared(x1, y1, x2, y2)
var x1 = argument[0];
var y1 = argument[1];
var x2 = argument[2];
var y2 = argument[3];
return (pow(pow(x2, 2) - pow(x1, 2), 2) + pow(pow(y2, 2) - pow(y1, 2), 2));
Then the code is pretty much the same, except you would need to square the radius, it would look something like this:
if (point_distance_squared(x, y, obj_player.x, obj_player.y) < (r * r)) {
//Mode towards the player
}
Upvotes: 1