How to move custum component by usetTick in react-pixi

51 views Asked by At

I'm trying to display moving rectangle by Pixi, React, and Typescript. I could observe the position value changed in useTick function by console.log, but the rectangle didn't move in screen.

Please let me know how to correct my code:

import { Container, PixiComponent, Stage, useTick} from '@pixi/react';
import { Graphics } from 'pixi.js';
import { useReducer, useRef } from 'react';

interface RectangleProps {
  x: number;
  y: number;
  width: number;
  height: number;
  color: number;
}
const Rectangle = PixiComponent<RectangleProps, Graphics>('Rectangle', {
  create: () => new Graphics(),
  applyProps: (ins, _, props) => {
    ins.x = props.x;
    ins.beginFill(props.color);
    ins.drawRect(props.x, props.y, props.width, props.height);
    ins.endFill();
  },
});

const initialState : RectangleProps= {
  x: 200,
  y: 100,
  width: 30,
  height: 30,
  color: 0x00ffff
};

interface Action {
  type: string;
  value: number;
}
const reducer = (state: RectangleProps, {value}: Action) => {
  state.x = 100*Math.cos(value) + 320;
  return state;
}

const MovingRectangle = () => {
  const [motion,update] = useReducer(reducer,initialState);
  const iter = useRef(0);
  useTick((delta) => {
    iter.current+=1;
    update({type: 'update', value:(iter.current*delta)});
  });
  return <Rectangle {...motion} />
};

const App = () => (
  <Stage>
    <Container>
      <MovingRectangle />
    </Container>
  </Stage>
);

export default App;
0

There are 0 answers