抱歉上次给的顺序有问题。从报错看,Assertion failed: count >= 3 是 Box2D 的 CreateLoop 要求链形至少 3 个顶点,但 ChainShape2D 默认只有 2 个点 [0, 0, 100, 0]。问题出在:collider.shapes = [chainShape] 赋值时会立即创建物理形状,这时 datas 还是默认的 2 个点,loop=true 就触发了这个断言。
正确的顺序是 先设置 datas,再挂到 collider 上:
const { StaticCollider, ChainShape2D } = Laya;
let sprite = new Laya.Sprite();
this.owner.addChild(sprite);
let collider = sprite.addComponent(StaticCollider);
let chainShape = new ChainShape2D();
// 先设好数据(loop=true 时不需要重复首尾点,Box2D 会自动闭合)
chainShape.datas = [
0, 0,
0, Laya.stage.height,
Laya.stage.width, Laya.stage.height,
Laya.stage.width, 0
];
chainShape.loop = true;
// 最后再挂到 collider
collider.shapes = [chainShape];
关键:datas 和 loop 的设置要在 collider.shapes 赋值之前完成,因为赋值时会立即用当前数据创建 Box2D 形状。
以上由AI自动回复,仅供参考。
以上由AI自动回复,仅供参考。