From 82dfc976e9b0d998ea33b6472522e269a6745973 Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 10 May 2024 17:51:08 +0800 Subject: [PATCH] simplify logic (#16966) * simplify logic * the same logic in c++ --- cocos/scene-graph/node.ts | 35 ++++++++++++++------------ native/cocos/core/scene-graph/Node.cpp | 4 +++ 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts index 421fe949fa..65bf67987c 100644 --- a/cocos/scene-graph/node.ts +++ b/cocos/scene-graph/node.ts @@ -2106,27 +2106,30 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable { public setPosition(x: number, y: number, z?: number): void; public setPosition (val: Readonly | number, y?: number, z?: number): void { - let x: number; const localPosition = this._lpos; - if (y === undefined && z === undefined) { - x = (val as Vec3).x; - y = (val as Vec3).y; - z = (val as Vec3).z; - } else if (z === undefined) { - x = val as number; - z = localPosition.z; + if (y === undefined) { + // The type of val is Readonly + if (localPosition.equals(val as Vec3)) { + return; + } + + Vec3.copy(this._lpos, val as Vec3); } else { - x = val as number; + if (z === undefined) { + z = localPosition.z; + } + + if (val as number === localPosition.x && y === localPosition.y && z === localPosition.z) { + return; + } + + Vec3.set(this._lpos, val as number, y, z); } - if (x !== localPosition.x || y !== localPosition.y || z !== localPosition.z) { - this._lpos.set(x, y, z); - this.invalidateChildren(TransformBit.POSITION); - - if (this._eventMask & TRANSFORM_ON) { - this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION); - } + this.invalidateChildren(TransformBit.POSITION); + if (this._eventMask & TRANSFORM_ON) { + this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION); } } diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index cf21dd6d60..788a0c0607 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -395,6 +395,10 @@ Node *Node::getChildByPath(const ccstd::string &path) const { // void Node::setPositionInternal(float x, float y, float z, bool calledFromJS) { + if (_localPosition.approxEquals({x, y, z})) { + return; + } + _localPosition.set(x, y, z); invalidateChildren(TransformBit::POSITION);