大家好!

我正在为GameMaker中的敌人AI开发一个简单的状态机,但我遇到了追逐/碰撞行为的问题。

问题:
当敌人接近玩家时,它并不会实际碰撞或攻击玩家。相反,它只是停在玩家旁边,什么也没发生。

代码:
以下是我的代码(每一步事件):

gml

if (point_distance(x, y, obj_player.x, obj_player.y) < 200) {
    speed = 0; 
    stato = "inseguimento";
} else {
    if (stato == "inseguimento") {
        speed = 0;
        stato = "ritorno";
    }
}

switch (stato) {
    case "fermo":
        if (alarm[0] == -1) {
            stato = "cammina";
        }
    break;

    case "cammina":
        if (point_distance(x, y, start_x, start_y) < raggio_massimo) {
            y += enemy_speed * direzione_verticale;
        } else {
            y -= enemy_speed * direzione_verticale;
            direzione_verticale = -direzione_verticale;
            stato = "fermo";
            alarm[0] = 2 * game_get_speed(gamespeed_fps);
        }
    break;

    case "inseguimento":
        move_towards_point(obj_player.x, obj_player.y, enemy_speed);
    break;

    case "ritorno":
        move_towards_point(start_x, start_y, enemy_speed);

        if (point_distance(x, y, start_x, start_y) < 2) {
            speed = 0; 
            x = start_x; 
            y = start_y;
            stato = "fermo"; 
            alarm[0] = 2 * game_get_speed(gamespeed_fps); 
        }
    break;
}

要正确触发碰撞或攻击状态,当敌人到达玩家时,需要重新组织此代码。感谢提前!

解决方案:

  1. 在“inseguimento”状态中添加一个条件,检查敌人是否已经到达玩家。
  2. 如果敌人已经到达玩家,切换到一个新的状态,例如“attacco”或“colpo”。
  3. 在“attacco”或“colpo”状态中,添加代码来触发碰撞或攻击动作。

修改后的代码:

gml

if (point_distance(x, y, obj_player.x, obj_player.y) < 200) {
    speed = 0; 
    stato = "inseguimento";
} else {
    if (stato == "inseguimento") {
        speed = 0;
        stato = "ritorno";
    }
}

switch (stato) {
    case "fermo":
        if (alarm[0] == -1) {
            stato = "cammina";
        }
    break;

    case "cammina":
        if (point_distance(x, y, start_x, start_y) < raggio_massimo) {
            y += enemy_speed * direzione_verticale;
        } else {
            y -= enemy_speed * direzione_verticale;
            direzione_verticale = -direzione_verticale;
            stato = "fermo";
            alarm[0] = 2 * game_get_speed(gamespeed_fps);
        }
    break;

    case "inseguimento":
        if (point_distance(x, y, obj_player.x, obj_player.y) < 10) { // 10是碰撞检测的阈值
            stato = "attacco";
        } else {
            move_towards_point(obj_player.x, obj_player.y, enemy_speed);
        }
    break;

    case "attacco":
        // 添加碰撞或攻击动作的代码
        // 例如:obj_player.attack();
        stato = "fermo";
        alarm[0] = 2 * game_get_speed(gamespeed_fps);
    break;

    case "ritorno":
        move_towards_point(start_x, start_y, enemy_speed);

        if (point_distance(x, y, start_x, start_y) < 2) {
            speed = 0; 
            x = start_x; 
            y = start_y;
            stato = "fermo"; 
            alarm[0] = 2 * game_get_speed(gamespeed_fps); 
        }
    break;
}

这将在敌人到达玩家时触发碰撞或攻击状态。请根据您的具体需求进行调整。