GameMaker: “flawed” AI path finding

In some cases, you may want object's AI to not pick exactly perfect path.

This example demonstrates creation of a basic "flawed" AI, that uses a rather plain method of finding path. Such will still make it reach destination in many cases, but will also allow player to "fool" the AI, making it stuck in dead ends or T-intersections (if player is standing right behind the wall).

To illustrate simplicity of concept, example is largely made in Drag & Drop.

Download

Quickly converted GML version:

Create Event:

    walk_speed = 4;
    walk_direction = 0;
    walk_distance = 0;

Step Event:

    // Movement:
    repeat (min(walk_speed, walk_distance)) {
        var nx = x + lengthdir_x(1, walk_direction);
        var ny = y + lengthdir_y(1, walk_direction);
        if (!place_meeting(nx, ny, obj_wall)) {
            x = nx;
            y = ny;
            walk_distance -= 1;
        } else break;
    }
    // Target catching:
    if (instance_number(obj_target) != 0) {
        target_x = obj_target.x;
        target_y = obj_target.y;
        event_user(0);
    }

Mouse Event for Glob Left Button:

    target_x = (mouse_x div 32) * 32;
    target_y = (mouse_y div 32) * 32;
    event_user(0);

Other Event: User Defined 0:

    if (walk_distance > 0) exit
    // Find difference
    var delta_x = target_x - x;
    var delta_y = target_y - y;
    // Signs
    var sign_x = sign(delta_x);
    var sign_y = sign(delta_y);
    // Reached the target already?
    if (delta_x == 0 && delta_y == 0) exit;
    // 
    walk_direction = -1;
    if (abs(delta_x) > abs(delta_y)) {
        if (!place_meeting(x + sign_x * 32, y, obj_wall)) {
            if (sign_x > 0) walk_direction = 0;
            if (sign_x < 0) walk_direction = 180;
        } else if (!place_meeting(x, y + sign_y * 32, obj_wall)) {
            if (sign_y > 0) walk_direction = 270;
            if (sign_y < 0) walk_direction = 90;
        }
    } else {
        if (!place_meeting(x, y + sign_y * 32, obj_wall)) {
            if (sign_y > 0) walk_direction = 270;
            if (sign_y < 0) walk_direction = 90;
        } else if (!place_meeting(x + sign_x * 32, y, obj_wall)) {
            if (sign_x > 0) walk_direction = 0;
            if (sign_x < 0) walk_direction = 180;
        }
    }
    // if direction have been set, move for one wall size worth:
    if (walk_direction != -1) walk_distance = 32;

Related posts:

4 thoughts on “GameMaker: “flawed” AI path finding

Leave a Reply

Your email address will not be published. Required fields are marked *