diff --git a/README.md b/README.md index 399e133..3b95ac5 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Component Props - as described by IJoystickProps - all are optional | baseShape | JoystickShape | The shape of the joystick default = circle| | controlPlaneShape | JoystickShape | Override the default shape behaviour of the control plane - circle, square, axisX, axisY| | minDistance | number | Percentage 0-100 - the minimum distance to start receive IJoystickMove events| - +| pos | {x: number, y: number}| Override the joystick position (doesn't work if the user is interacting. You can use `disabled` to force this)| ```TypeScript import {JoystickShape} from "./shape.enum"; interface IJoystickProps { @@ -61,6 +61,7 @@ interface IJoystickProps { stickShape?: JoystickShape; controlPlaneShape?: JoystickShape; minDistance?: number; + pos: {x: number, y: number} } ``` diff --git a/src/Joystick.stories.tsx b/src/Joystick.stories.tsx index 371882e..ca4127c 100644 --- a/src/Joystick.stories.tsx +++ b/src/Joystick.stories.tsx @@ -31,6 +31,27 @@ joystickStories.add("Yellow (custom colors) joystick", stickColor={"#FFD300"} move={action("Moved")} stop={action("Stopped")}/>); +joystickStories.add("Position override", +() => ); + + joystickStories.add("Position override with second joystick", +() => { +const [joystickPos, setJoystickPos] = useState({x:0, y:0}); +const handleMove = (event) => { + setJoystickPos({x: event.x, y: event.y}) +}; +return <> + + + + +;}); + joystickStories.add("Y Axis only", () => { // expect(moveCallback).not.toHaveBeenCalled(); // }); + + + test('renders the joystick stick at the correct position when the pos prop is provided', () => { + const pos = { x: 0.4, y: -0.6 }; + const size = 100; + const expectedStickPosition = { + x: (pos.x * size) / 2, + y: -(pos.y * size) / 2, + }; + + render(); + const stick = screen.getByRole('button'); + + expect(stick).toHaveStyle({ + transform: `translate3d(${expectedStickPosition.x}px, ${expectedStickPosition.y}px, 0)`, + }); + }); }); diff --git a/src/Joystick.tsx b/src/Joystick.tsx index d273fda..06b1efe 100644 --- a/src/Joystick.tsx +++ b/src/Joystick.tsx @@ -21,6 +21,7 @@ export interface IJoystickProps { stickShape?: JoystickShape; controlPlaneShape?: JoystickShape; minDistance?: number; + pos?: {x: number, y: number}; } enum InteractionEvents { @@ -382,6 +383,12 @@ class Joystick extends React.Component { stickStyle.background = `url(${this.props.stickImage})`; stickStyle.backgroundSize = '100%' } + if(this.props.pos){ + stickStyle = Object.assign({}, stickStyle, { + position: 'absolute', + transform: `translate3d(${(this.props.pos.x * this._baseSize)/2 }px, ${-(this.props.pos.y * this._baseSize)/2}px, 0)` + }); + } if (this.state.coordinates !== undefined) { stickStyle = Object.assign({}, stickStyle, {