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

Phaser3中基于Matter Physics计算物理形状与点的水平距离

计算Phaser 3中Matter物理形状与目标点的水平距离

核心思路

你需要的水平距离,本质是物理形状的轴对齐包围盒(AABB)与目标点在x轴上的最短间隔。Matter Physics已经为每个Body计算好了对应的AABB,直接使用即可,无需手动处理顶点的旋转、缩放和坐标转换。

实现代码

假设你已经创建了chisatoLeft这个Matter Image对象,目标点为全局坐标{x: targetX, y: targetY},代码如下:

// 定义目标点的全局坐标
const targetPoint = { x: 600, y: 425 };

// 获取物理对象的轴对齐包围盒
const bodyBounds = chisatoLeft.body.bounds;
const shapeLeftEdge = bodyBounds.min.x; // 形状最左侧全局X
const shapeRightEdge = bodyBounds.max.x; // 形状最右侧全局X

let horizontalDistance = 0;

// 根据目标点位置计算水平距离
if (targetPoint.x > shapeRightEdge) {
  // 目标点在形状右侧,距离为点X减去形状最右X
  horizontalDistance = targetPoint.x - shapeRightEdge;
} else if (targetPoint.x < shapeLeftEdge) {
  // 目标点在形状左侧,距离为形状最左X减去点X
  horizontalDistance = shapeLeftEdge - targetPoint.x;
} else {
  // 目标点在形状的水平投影范围内,水平距离为0
  horizontalDistance = 0;
}

// 输出结果
console.log('水平距离:', horizontalDistance);

关键说明

  1. AABB的自动更新:Matter会自动维护body.bounds的值,无论对象是否旋转、缩放或移动,都能实时获取到最新的形状边界。
  2. 顶点坐标的备选方案:如果你需要基于原始多边形顶点(而非包围盒)计算,可通过chisatoLeft.body.vertices获取所有顶点的全局坐标,遍历后找出最小/最大X值,逻辑和上述一致:
    const vertices = chisatoLeft.body.vertices;
    const xCoords = vertices.map(v => v.x);
    const shapeLeftEdge = Math.min(...xCoords);
    const shapeRightEdge = Math.max(...xCoords);
    
    这种方式和使用bounds结果一致,但bounds是Matter预计算的,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:55:16