Matter.js中fromVertices定位三角形位置偏移问题求助
问题描述
我尝试将两个三角形定位成贴合画布边缘的目标样式,做了如下操作:
- 定义三角形尺寸:
const funnelHeight = 100; const funnelWidth = (this.sizes.w - pipe) / 2;
- 设定左侧三角形的几何中心点为:
funnelWidth / 2, this.sizes.h - funnelHeight / 2 - 基于该中心点定义三角形顶点:
const leftFunnel = [ {x: -funnelWidth / 2, y: - funnelHeight / 2}, {x: funnelWidth / 2, y: funnelHeight / 2}, {x: -funnelWidth / 2, y: funnelHeight / 2}, ];
- 通过Matter.js将形状添加到场景:
this.leftFunnel = Bodies.fromVertices(funnelWidth / 2, this.sizes.h - funnelHeight / 2, leftFunnel , { isStatic: true});
实际效果中三角形偏离了画布边缘,后续测试发现矩形形状定位完全正常,推测问题出在Matter.js以重心为基准定位,而非几何中心点。请问哪里操作出错了?
解决方案
你的推测完全正确——Matter.js中Bodies.fromVertices默认以形状的**重心(质心)**作为定位锚点,而非你设定的几何中心点。
问题根源
你定义的三角形三个顶点为:
(-funnelWidth/2, -funnelHeight/2)(funnelWidth/2, funnelHeight/2)(-funnelWidth/2, funnelHeight/2)
根据三角形重心公式(三个顶点坐标的平均值),计算得该三角形的重心坐标为:
重心x = (-w/2 + w/2 - w/2) / 3 = -w/6 重心y = (-h/2 + h/2 + h/2) / 3 = h/6
(其中w = funnelWidth,h = funnelHeight)
这说明你定义的顶点相对于重心存在偏移,当你用几何中心点坐标放置时,整个形状会因重心偏移而错位。
两种解决方法
方法1:调整顶点坐标,让重心与几何中心点对齐
修改顶点定义,使三角形的重心落在你期望的几何中心(0,0)位置:
const leftFunnel = [ {x: -funnelWidth / 2, y: -funnelHeight / 2}, {x: funnelWidth / 2, y: -funnelHeight / 2}, {x: -funnelWidth / 2, y: funnelHeight / 2}, ];
方法2:补偿重心偏移,调整放置坐标
既然重心相对于你设定的几何中心点的偏移量是(-funnelWidth/6, funnelHeight/6),则将放置坐标反向补偿该偏移,让重心落在目标位置:
const centroidXOffset = -funnelWidth / 6; const centroidYOffset = funnelHeight / 6; this.leftFunnel = Bodies.fromVertices( funnelWidth / 2 - centroidXOffset, this.sizes.h - funnelHeight / 2 - centroidYOffset, leftFunnel, { isStatic: true } );
也可以启用Matter.js的调试模式,直观查看重心位置辅助调试,或使用Matter.Body.setPosition方法先创建形状再调整位置。
内容的提问来源于stack exchange,提问作者Djave
相关产品推荐
相关产品推荐

