Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created April 6, 2021 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whoisryosuke/5216a4abf52dfbaa095de9ab6fc3dd5c to your computer and use it in GitHub Desktop.
Save whoisryosuke/5216a4abf52dfbaa095de9ab6fc3dd5c to your computer and use it in GitHub Desktop.
AFrame / React / AnimeJS - useAnimation hook for animating A-Frame's Entities. Uses the ThreeJS Object3D properties for performance.
import React, { useLayoutEffect, useRef } from "react";
export type VectorCoordinate = {
x: number;
y: number;
z: number;
};
export type useAnimationProps = {
from: {
[key: string]: VectorCoordinate | number | string;
};
to: {
[key: string]: VectorCoordinate | number | string;
};
delay?: number;
};
export const useAnimation = ({ from, to, delay }: useAnimationProps) => {
const boxRef = useRef<any>(null);
const animations = useRef<any>({});
useLayoutEffect(() => {
if (boxRef?.current?.el && Object.keys(animations.current).length <= 0) {
Object.keys(to).forEach((prop) => {
// Detect if we need to destructure
const isObject = prop === "position" || prop === "rotation";
const parseFrom = isObject ? from[prop] : { [prop]: from[prop] };
const parseTo = isObject ? to[prop] : { [prop]: to[prop] };
animations.current[prop] = AFRAME.ANIME({
targets: parseFrom,
//@ts-ignore
...parseTo,
loop: true,
direction: "alternate",
update: function () {
if (prop === "position" || prop === "rotation") {
Object.keys(from[prop]).forEach((propKey) => {
//@ts-ignore
boxRef.current.el.object3D[prop][propKey] = from[prop][propKey];
});
}
if (prop === "opacity" || prop === "color") {
boxRef.current.el.components.material.material[prop] = from[prop];
}
},
});
});
}
}, [from, to]);
return {
ref: boxRef,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment