You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GameMaker 2中如何使用move_and_collide实现多对象碰撞?

解决move_and_collide同时检测多类对象(无需父对象)

1. 修正数组创建错误

你当前代码的核心问题是array_push的返回值是数组的长度而非数组本身,导致objectsToCollide实际是数值2,无法被move_and_collide识别为碰撞对象集合。正确的数组创建方式有两种:

方式一:数组字面量(推荐)

直接用方括号定义包含目标对象的数组:

objectsToCollide = [oWall, oEnemy];
move_and_collide(xSpeed, ySpeed, objectsToCollide);

方式二:分步创建数组

先初始化空数组,再通过array_push添加元素,注意要先将数组赋值给变量:

objectsToCollide = array_create(0);
array_push(objectsToCollide, oWall, oEnemy);
move_and_collide(xSpeed, ySpeed, objectsToCollide);

2. 版本兼容性说明

move_and_collide支持数组作为碰撞对象参数是GameMaker Studio 2.3及以上版本的特性。如果你的版本低于此,需要使用以下替代方案。

3. 低版本替代实现(无需父对象)

方案A:预检测碰撞再移动

先通过矩形碰撞检测预判是否会与目标对象碰撞,再决定移动逻辑:

// 计算移动后的碰撞范围
var _newX = x + xSpeed;
var _newY = y + ySpeed;
var _left = _newX;
var _top = _newY;
var _right = _newX + sprite_width;
var _bottom = _newY + sprite_height;

// 依次检测两类对象
var _hasCollision = collision_rectangle(_left, _top, _right, _bottom, oWall, false, true);
if (!_hasCollision) {
    _hasCollision = collision_rectangle(_left, _top, _right, _bottom, oEnemy, false, true);
}

// 执行移动或碰撞处理
if (_hasCollision) {
    // 这里添加碰撞后的逻辑(比如停止移动、反弹等)
} else {
    x = _newX;
    y = _newY;
}

方案B:分两次调用move_and_collide

先与第一类对象碰撞,再用剩余速度与第二类对象碰撞:

var _remainX = xSpeed;
var _remainY = ySpeed;

// 先处理与oWall的碰撞
var _collided = move_and_collide(_remainX, _remainY, oWall);
if (_collided) {
    // 获取碰撞后剩余的速度
    _remainX = move_get_x_speed();
    _remainY = move_get_y_speed();
}

// 再处理与oEnemy的碰撞
move_and_collide(_remainX, _remainY, oEnemy);

内容的提问来源于stack exchange,提问作者Andrei Statescu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:39:55