基于p5.js的2D游戏引擎:如何从世界位置推导本地位置?
从世界坐标反推本地坐标的实现方案
你当前的正向变换逻辑是:将本地坐标叠加到父对象的世界坐标后,绕父对象的世界位置旋转,最终得到自身世界坐标。要实现逆变换(从世界坐标求本地坐标),只需要把正向步骤倒过来执行即可,完全不需要用矩阵,以下是具体实现:
SetLocalFromWorld() { // 获取父对象的Transform组件 const parentTransform = ScriptingAPI.getComponentByName(this.engineAPI, this.gameObject.parent, "Transform"); // 无父对象的边界情况:本地坐标直接等于世界坐标 if (!parentTransform) { this.localPosition = {...this.worldPosition}; this.localRotation = this.worldRotation; this.localScale = {...this.worldScale}; return; } const parentPosition = parentTransform.worldPosition; const parentRotation = parentTransform.worldRotation; const degToRad = Math.PI / 180; // 逆旋转角度:用负角度等价于反向旋转,抵消父旋转的影响 const inverseRotation = -parentRotation * degToRad; // 第一步:将世界坐标相对于父世界坐标做逆旋转 const dx = this.worldPosition.x - parentPosition.x; const dy = this.worldPosition.y - parentPosition.y; const rotatedBackX = dx * Math.cos(inverseRotation) - dy * Math.sin(inverseRotation); const rotatedBackY = dx * Math.sin(inverseRotation) + dy * Math.cos(inverseRotation); // 第二步:减去父世界坐标,得到本地坐标 this.localPosition = { x: rotatedBackX, y: rotatedBackY }; // 旋转的逆运算:反向相减 this.localRotation = this.worldRotation - parentTransform.worldRotation; // 若后续支持父缩放传递,需改为 this.worldScale.x / parentTransform.worldScale.x this.localScale = {...this.worldScale}; }
逻辑说明
- 无父对象处理:如果对象没有父节点,本地坐标与世界坐标完全等价,直接赋值即可。
- 逆旋转抵消:正向变换用父旋转角度对坐标做了旋转,逆变换用负角度旋转一次,就能把坐标拉回父对象未旋转时的空间。
- 平移逆运算:抵消旋转后,将坐标减去父对象的世界位置,就能得到相对于父对象的本地坐标。
- 旋转与缩放扩展:
- 旋转逆运算直接用自身世界旋转减去父世界旋转,和正向的加法逻辑对应。
- 你当前代码未处理父缩放的传递(
this.worldScale = this.localScale),若后续要支持父缩放影响世界缩放,本地缩放需改为this.worldScale.x / parentTransform.worldScale.x、this.worldScale.y / parentTransform.worldScale.y。
内容的提问来源于stack exchange,提问作者Bennett Friesen
相关产品推荐
相关产品推荐

