Skip to content

Instantly share code, notes, and snippets.

@al-arz
Created August 22, 2024 13:20
Show Gist options
  • Save al-arz/9db8fadbf4fcbca694f6e3e0d0929f17 to your computer and use it in GitHub Desktop.
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.
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