fix get angle problem (#399)

* fix get angle problem

* fix eslint

* use new function to get angle

* fix eslint error
This commit is contained in:
zxx43
2026-11-11 16:04:02 +08:00
committed by GitHub
parent 7037052b40
commit 4a0dbc977a
6 changed files with 140 additions and 3 deletions
+9 -1
View File
@@ -28,7 +28,7 @@ import { NodeEventType } from './node-event';
import { CCObjectFlags } from '../core/data/object';
import { NodeUIProperties } from './node-ui-properties';
import { MobilityMode, NodeSpace, TransformBit } from './node-enum';
import { IVec2Like, Mat4, Quat, Vec3 } from '../core/math';
import { EPSILON, IVec2Like, Mat4, Quat, toDegree, Vec3 } from '../core/math';
import { Layers } from './layers';
import { editorExtrasTag, SerializationContext, SerializationOutput, serializeTag } from '../core/data';
import { _tempFloatArray, fillMat4WithTempFloatArray } from './utils.jsb';
@@ -692,6 +692,14 @@ nodeProto.setPosition = function setPosition(val: Readonly<Vec3> | number, y?: n
this._setPosition();
};
nodeProto.getAngle2D = function getAngle2D(): number {
const { x, y, z, w } = this._lrot;
if (Math.abs(x) < EPSILON && Math.abs(y) < EPSILON) {
return toDegree(Math.atan2(2 * w * z, 1 - 2 * z * z));
}
return this.eulerAngles.z;
};
nodeProto.getRotation = function getRotation(out?: Quat): Quat {
const lrot = this._lrot;
if (out) {
+19 -1
View File
@@ -29,7 +29,7 @@ import { NodeUIProperties } from './node-ui-properties';
import { cclegacy } from '../core/global-exports';
import { nodePolyfill } from './node-dev';
import { ISchedulable } from '../core/scheduler';
import { approx, EPSILON, Mat3, mat4, Mat4, quat, Quat, v3, Vec3 } from '../core/math';
import { approx, EPSILON, Mat3, mat4, Mat4, quat, Quat, toDegree, v3, Vec3 } from '../core/math';
import { MobilityMode, NodeSpace, TransformBit } from './node-enum';
import { CustomSerializable, editorExtrasTag, SerializationContext, SerializationOutput, serializeTag } from '../core/data';
import { errorID, warnID, error, log, getError } from '../core/platform/debug';
@@ -59,6 +59,7 @@ const ACTIVE_ON = 1 << 1;
const idGenerator = new js.IDGenerator('Node');
/* eslint-disable-next-line max-len */
function getConstructor<T> (typeOrClassName: string | Constructor<T> | AbstractedConstructor<T>): Constructor<T> | AbstractedConstructor<T> | null | undefined {
if (!typeOrClassName) {
errorID(3804);
@@ -316,6 +317,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
return null;
}
/* eslint-disable-next-line max-len */
protected static _findComponents<T extends Component> (node: Node, constructor: Constructor<T> | AbstractedConstructor<T>, components: Component[]): void {
const cls = constructor;
const comps = node._components;
@@ -1847,6 +1849,22 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
}
}
/**
* @en Gets the signed local Z rotation in degrees for 2D nodes, in [-180, 180].
* Full turns are not preserved. For non-planar rotations, returns the Euler Z component.
* @zh 获取二维节点的本地 Z 轴有符号旋转角度,范围为 [-180, 180],不保留累计圈数。
* 非平面旋转返回欧拉角的 Z 分量。
*/
public getAngle2D (): number {
// YZX Euler decomposition folds Z into [-90, 90]. For a 2D rotation,
// extract the signed angle directly, without changing the 3D Euler cache.
const { x, y, z, w } = this._lrot;
if (Math.abs(x) < EPSILON && Math.abs(y) < EPSILON) {
return toDegree(Math.atan2(2 * w * z, 1 - 2 * z * z));
}
return this.eulerAngles.z;
}
/**
* @en Rotation in world coordinate system, represented by a quaternion
* @zh 世界坐标系下的旋转,用四元数表示
+13
View File
@@ -24,6 +24,8 @@
#pragma once
#include <cmath>
#include "base/Ptr.h"
#include "base/std/any.h"
#include "bindings/utils/BindingUtils.h"
@@ -34,6 +36,7 @@
#include "core/scene-graph/Layers.h"
#include "core/scene-graph/NodeEnum.h"
#include "math/Mat3.h"
#include "math/Math.h"
#include "math/Mat4.h"
#include "math/Quaternion.h"
#include "math/Vec3.h"
@@ -434,6 +437,16 @@ public:
return getEulerAngles().z;
}
// Signed local 2D angle in degrees, normalized to [-180, 180].
inline float getAngle2D() const {
// Keep 2D angles independent of the folded Z in YZX Euler decomposition.
const auto &q = _localRotation;
if (std::abs(q.x) < 1e-6F && std::abs(q.y) < 1e-6F) {
return std::atan2(2.F * q.w * q.z, 1.F - 2.F * q.z * q.z) * math::RAD_TO_DEG;
}
return getEulerAngles().z;
}
inline Vec3 getForward() const {
Vec3 forward{0, 0, -1};
forward.transformQuat(getWorldRotation());
+23
View File
@@ -216,4 +216,27 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) {
0, 0, 0, 1)));
}
TEST(NodeTest, angleAfterQuaternionWriteback) {
cc::IntrusivePtr<cc::Node> node(new Node());
for (const float angle : {-179.F, -120.F, -91.F, -90.F, 90.F, 91.F, 120.F, 179.F}) {
const float halfAngle = angle * math::DEG_TO_RAD * 0.5F;
const Quaternion rotation(0.F, 0.F, std::sin(halfAngle), std::cos(halfAngle));
node->setRotation(rotation);
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
const Vec3 euler = node->getEulerAngles();
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
EXPECT_TRUE(node->getEulerAngles().approxEquals(euler));
node->setRotation(Quaternion(-rotation.x, -rotation.y, -rotation.z, -rotation.w));
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
}
node->setAngle(720.F);
EXPECT_FLOAT_EQ(node->getAngle(), 720.F);
EXPECT_NEAR(node->getAngle2D(), 0.F, 1e-4F);
const float halfAngle = 60.F * math::DEG_TO_RAD;
node->setRotation(Quaternion(0.F, 0.F, std::sin(halfAngle), std::cos(halfAngle)));
EXPECT_NEAR(node->getAngle2D(), 120.F, 1e-4F);
EXPECT_NEAR(node->getAngle(), 60.F, 1e-4F);
EXPECT_NEAR(node->getAngle2D(), 120.F, 1e-4F);
}
} // namespace
+44
View File
@@ -666,6 +666,50 @@ describe(`Node`, () => {
))).toBeTruthy();
});
test.each([-179, -120, -91, -90, 90, 91, 120, 179])('2D angle after quaternion writeback: %s', (angle) => {
const node = new Node();
const rotation = Quat.fromAngleZ(new Quat(), angle);
node.setRotation(rotation);
expect(node.getAngle2D()).toBeCloseTo(angle);
// Reading the 3D Euler cache first must not change the 2D angle.
const euler = node.eulerAngles.clone();
expect(node.getAngle2D()).toBeCloseTo(angle);
expect(Vec3.equals(node.eulerAngles, euler)).toBe(true);
node.setRotation(new Quat(-rotation.x, -rotation.y, -rotation.z, -rotation.w));
expect(node.getAngle2D()).toBeCloseTo(angle);
});
test('angle keeps legacy Euler results independently of getAngle2D', () => {
const node = new Node();
node.setRotation(Quat.fromAngleZ(new Quat(), 120));
expect(node.getAngle2D()).toBeCloseTo(120);
expect(node.angle).toBeCloseTo(60);
expect(node.getAngle2D()).toBeCloseTo(120);
expect(node.angle).toBeCloseTo(60);
});
test('getAngle2D stays local under a rotated parent', () => {
const parent = new Node();
const node = new Node();
parent.addChild(node);
parent.angle = 30;
node.setWorldRotationFromEuler(0, 0, 150);
expect(node.getAngle2D()).toBeCloseTo(120);
});
test('angle preserves explicit full turns and 3D Euler behavior', () => {
const node = new Node();
node.angle = 720;
expect(node.angle).toBe(720);
expect(node.getAngle2D()).toBeCloseTo(0);
const rotation = Quat.fromEuler(new Quat(), 30, 40, 120);
node.setRotation(rotation);
const euler = Quat.toEuler(new Vec3(), rotation);
expect(node.angle).toBeCloseTo(euler.z);
expect(node.getAngle2D()).toBeCloseTo(euler.z);
expect(node.eulerAngles).toEqual(euler);
});
test ('angle', ()=> {
let node = new Node();
+32 -1
View File
@@ -11,6 +11,37 @@ export default function (parent: Node, _steps = 0) {
if (physics2d.selector.id === 'builtin')
return;
// Regression: physics writeback must not fold getAngle2D() at +/-90 degrees.
for (const type of [physics2d.ERigidBody2DType.Dynamic, physics2d.ERigidBody2DType.Kinematic]) {
for (const enabled of [true, false]) {
const node = new Node('AngleRegression');
parent.addChild(node);
const body = node.addComponent(physics2d.RigidBody2D);
body.type = type;
body.gravityScale = 0;
body.enabled = enabled;
const dt = physics2d.PhysicsSystem2D.instance.fixedTimeStep;
for (const angle of [-179, -120, -91, 91, 120, 179]) {
node.angle = angle;
director.tick(dt);
expect(node.getAngle2D()).toBeCloseTo(angle, 3);
expect(Math.abs(Quat.dot(node.worldRotation, Quat.fromAngleZ(new Quat(), angle)))).toBeCloseTo(1);
}
// Exercise read/modify/write across both 90 degrees and full turns.
for (const delta of [10, -10]) {
node.angle = 0;
for (let step = 1; step <= 40; ++step) {
node.angle = node.getAngle2D() + delta;
director.tick(dt);
const expected = Quat.fromAngleZ(new Quat(), step * delta);
expect(Math.abs(Quat.dot(node.worldRotation, expected))).toBeCloseTo(1);
}
}
node.destroy();
director.tick(dt);
}
}
// basic api
{
const nodeRigidBody = new Node('RigidBody');
@@ -191,4 +222,4 @@ export default function (parent: Node, _steps = 0) {
director.tick(0.2);//make sure is destroyed
}
}
}
}