Created
August 22, 2024 13:20
-
-
Save al-arz/9db8fadbf4fcbca694f6e3e0d0929f17 to your computer and use it in GitHub Desktop.
A common task in pixi.js games is to change the parent of a Container (move it within the scene graph) without altering its on-screen position. Here's the snippet for that.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Container from "pixi.js"; | |
function getLocalPos(target: Container, parent: Container): void { | |
return parent.toLocal(target.parent.toGlobal(target.position)); | |
} | |
// Change target's parent but preserve its screen position | |
function changeParent(target: Container, parent: Container): void { | |
const position = getLocalPos(target, parent); | |
parent.addChild(target); | |
target.position.copyFrom(position); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment