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

如何检测Matter.js中的Body对象是否为圆形?

判断Matter.js物体是否为圆形

在Matter.js中没有官方直接的检测方法,但可以通过物体的形状属性来判断:

  • 通过Matter.Bodies.circle()创建的圆形物体,其part对应的shape对象会带有type: 'circle'标识,同时还会包含radius属性。

修改你的示例代码如下:

const compounds = Matter.Composite.allBodies(engine.world)
compounds.forEach(compound => compound.parts.forEach(part => {
  // 判断是否为圆形:检查shape的type是否为'circle'
  const isCircle = part.shape?.type === 'circle';
  if (isCircle) console.log(part.id, 'is a circle')
  else console.log(part.id, 'is not a circle')
}))

补充说明

  • 优先使用shape.type判断更准确,若需兼容旧版本Matter.js,也可辅助检查part.shape是否存在radius属性,但部分自定义形状可能也会带有该属性,需注意区分。
  • 注意:你代码里的new Matter.Body.Circle是错误写法,Matter.js中创建圆形物体的正确方式是Matter.Bodies.circle(x, y, radius, [options])。

内容的提问来源于stack exchange,提问作者David Y. Stephenson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:24:19