npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

go1-react-three-game-engine

v0.13.3

Published

A very early experimental work-in-progress package to help provide game engine functionality for react-three-fiber

Downloads

7

Readme

react-three-game-engine

Version Downloads

A very early experimental work-in-progress package to help provide game engine functionality for react-three-fiber.

Key Features

  • planck.js 2d physics integration
  • Physics update rate independent of frame rate
  • OnFixedUpdate functionality
  • Additional React app running in web worker, sync'd with physics, for handling game logic etc

I will be working on an example starter-kit: react-three-game-starter which will be fleshed out over time.

Note

The planck.js integration currently isn't fully fleshed out. I've only been adding in support for functionality on an as-needed basis for my own games.

Note: if you delve into the source code for this package, it's a bit messy!

Note: right now I'm having issues getting this to run via codesandbox via create-react-app, hopefully I can resolve this eventually.

Get Started

General / Physics

  1. Install required packages

npm install react-three-game-engine

plus

npm install three react-three-fiber planck-js

  1. Import and add <Engine/> component within your r3f <Canvas/> component.
import { Engine } from 'react-three-game-engine'
import { Canvas } from 'react-three-fiber'
<Canvas>
    <Engine>
        {/* Game components go here */}
    </Engine>
</Canvas>
  1. Create a planck.js driven physics body
import { useBody, BodyType, BodyShape } from 'react-three-game-engine'
import { Vec2 } from 'planck-js'
const [ref, api] = useBody(() => ({
    type: BodyType.dynamic,
    position: Vec2(0, 0),
    linearDamping: 4,
    fixtures: [{
        shape: BodyShape.circle,
        radius: 0.55,
        fixtureOptions: {
            density: 20,
        }
    }],
}))
  1. Control the body via the returned api
api.setLinearVelocity(Vec2(1, 1))
  1. Utilise useFixedUpdate for controlling the body
import { useFixedUpdate } from 'react-three-game-engine'

const velocity = Vec2(0, 0)

// ...

const onFixedUpdate = useCallback(() => {

    // ...

    velocity.set(xVel * 5, yVel * 5)
    api.setLinearVelocity(velocity)

}, [api])

useFixedUpdate(onFixedUpdate)

React Logic App Worker

A key feature provided by react-three-game-engine is the separate React app running within a web worker. This helps keep the main thread free to handle rendering etc, helps keep performance smooth.

To utilise this functionality you'll need to create your own web worker. You can check out my repo react-three-game-starter for an example of how you can do so with create-react-app without having to eject.

  1. Create a React component to host your logic React app, export a new component wrapped with withLogicWrapper
import {withLogicWrapper} from "react-three-game-engine";

const App = () => {
    // ... your new logic app goes here
}

export const LgApp = withLogicWrapper(App)
  1. Set up your web worker like such (note requiring the file was due to jsx issues with my web worker compiler)
/* eslint-disable no-restricted-globals */
import {logicWorkerHandler} from "react-three-game-engine";

// because of some weird react/dev/webpack/something quirk
(self).$RefreshReg$ = () => {};
(self).$RefreshSig$ = () => () => {};

logicWorkerHandler(self, require("../path/to/logic/app/component").LgApp)
  1. Import your web worker (this is just example code)
const [logicWorker] = useState(() => new Worker('../path/to/worker', { type: 'module' }))
  1. Pass worker to <Engine/>
<Engine logicWorker={logicWorker}>
    {/* ... */}
</Engine>

You should now have your Logic App running within React within your web worker, synchronised with the physics worker as well.

Controlling a body through both the main, and logic apps.

To control a body via either the main or logic apps, you would create the body within one app via useBody and then within the other app you can get api access via useBodyApi.

However you need to know the uuid of the body you wish to control. By default the uuid is one generated via threejs, but you can specify one yourself.

  1. Create body
useBody(() => ({
    type: BodyType.dynamic,
    position: Vec2(0, 0),
    linearDamping: 4,
    fixtures: [{
        shape: BodyShape.circle,
        radius: 0.55,
        fixtureOptions: {
            density: 20,
        }
    }],
}), {
    uuid: 'player'
})
  1. Get body api
const api = useBodyApi('player')

// ...

api.setLinearVelocity(Vec2(1, 1))

So with this approach, you can for example initiate your player body via the logic app, and then get api access via the main app, and use that to move the body around.

  1. Additionally, if you are creating your body in main / logic, you'll likely want to have access to the position / rotation of the body as well.

You can use useSubscribeMesh and pass in a ref you've created, which will synchronize with the physics body.

const ref = useRef<Object3D>(new Object3D())
useSubscribeMesh('player', ref.current, false)

// ...

return (
    <group ref={ref}>
        {/*...*/}
    </group>
)

Synchronising Logic App with Main App

I've added in useSyncWithMainComponent to sync from the logic app to the main app

  1. Within a component running on the logic app
const updateProps = useSyncWithMainComponent("player", "uniqueKey", {
    foo: "bar"
})

// ...

updateProps({
    foo: "updated"
})

  1. Then within the main app
const Player = ({foo}) => {
    // foo -> "bar"
    // foo -> "updated"
}

const mappedComponents = {
    "player": Player
}

<Engine logicWorker={logicWorker} logicMappedComponents={mappedComponents}>
    {/* ... */}
</Engine>

When useSyncWithMainComponent is mounted / unmounted, the <Player/> component will mount / unmount.

Note: currently this only supports sync'ing from logic -> main, but I will add in the reverse soon.

Communication

To communicate between the main and logic workers you can use useSendMessage to send and useOnMessage to subscribe

import {useSendMessage} from "react-three-game-engine"

// ...

const sendMessage = useSendMessage()

// ...

sendMessage('messageKey', "any-data")
import {useOnMessage} from "react-three-game-engine"

// ...

const onMessage = useOnMessage()

// ...

const unsubscribe = onMessage('messageKey', (data) => {
  // data -> "any-data"
})

// ...

unsubscribe()

API

Read the API documentation