Skip to content

Instantly share code, notes, and snippets.

@trezy
Last active December 8, 2024 06:31
Show Gist options
  • Save trezy/a56093ca239116cfb07a8a01c473ac01 to your computer and use it in GitHub Desktop.
Save trezy/a56093ca239116cfb07a8a01c473ac01 to your computer and use it in GitHub Desktop.
export function Player() {
const {
positionX,
positionY,
velocityX,
velocityY,
} = useStore(store)
const [isFlipped, setIsFlipped] = useState(false)
const spriteRef = useRef(null)
const spritesheet = useMemo(() => {
return Assets.get('hero.json')
}, [])
const textures = useMemo(() => {
if (velocityX || velocityY) {
return spritesheet.animations['run']
}
return spritesheet.animations['idle']
}, [
velocityX,
velocityY,
spritesheet,
])
useEffect(() => {
if (velocityX === -1) {
setIsFlipped(true)
} else if (velocityX === 1) {
setIsFlipped(false)
}
}, [velocityX])
useEffect(() => {
if (spriteRef.current) {
spriteRef.current.play()
}
}, [textures])
return (
<container
x={positionX}
y={positionY}>
<animatedSprite
ref={spriteRef}
animationSpeed={0.2}
scale={{
x: isFlipped ? -1 : 1,
y: 1
}}
textures={textures} />
</container>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment