• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Avoiding Obstacles

A

Arachnis

Guest
Hello everybody,

I have a bit of code to share. Maybe you guys could help me fix my problem.

I am trying to make my AI characters avoid circular (I will add more shapes later) obstacles by going around them. The way I tried to achieve this is with vectors. I have one vector, which is the ahead vector, another one pointing to the obstacle ahead and then I project from the obstacle's center onto the ahead vector and then substract the obstacle center from the projection vector to get the avoidance vector which I then add to the velocity. So my plan is to check, on which side of the obstacle the ahead vector is on, and then to "push" the velocity sidewards, away from the center.

The avoidance vector ought to form a right angle with the vector from the player to the obstacle's center, but apparently I did something wrong.

This is the code:

///scr_Collision_Detection(object)

if instance_exists(argument[0])
{
//get length of velocity vector
var vx = velocity[0] - x;
var vy = velocity[1] - y;
var len = abs(vx) + abs(vy);

//divide length of velocity by movespeed to get dynamic_length
var dynamic_length = len/moveSpeed;

//ahead vector
var ax = position[0] + velocity[0] * dynamic_length;
var ay = position[1] + velocity[1] * dynamic_length;

var inst = scr_collision_line_first(x,y,ax,ay,argument[0],false,true);
if inst != noone
{
//vector to the obstacle u
var ux = inst.x - x;
var uy = inst.y - y;

//get length of a
var alen = abs(ax) + abs(ay);

//project vector u on a
var projax = (ux*ax/sqr(alen))*ax;
var projay = (uy*ay/sqr(alen))*ay;

avoidance[0] = projax - ux;
avoidance[1] = projay - uy;

//get avoidance length
var avlen = abs(avoidance[0]) + abs(avoidance[1]);

//normalize avoidance
avoidance[0] = avoidance[0]/avlen;
avoidance[1] = avoidance[1]/avlen;

avoidance[0] = avoidance[0] * (inst.radius + sprite_width/2);
avoidance[1] = avoidance[1] * (inst.radius + sprite_height/2);
}
else
{
avoidance[0] = 0;
avoidance[1] = 0;
}
}
return avoidance;

But instead of avoiding the object by going to it's side (like, making a curve around it), the avoidance will push the AI characters directly away from the object.

Can anyone help?

Greetings
 
Last edited by a moderator:
Top