Skip to content

Commit

Permalink
fix: billboard
Browse files Browse the repository at this point in the history
  • Loading branch information
drcmda committed Dec 14, 2023
1 parent 5c4f60e commit 272b015
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/core/Billboard.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as React from 'react'
import { Group } from 'three'
import { Group, Quaternion } from 'three'
import { useFrame } from '@react-three/fiber'
import mergeRefs from 'react-merge-refs'
import { ForwardRefComponent } from '../helpers/ts-utils'

export type BillboardProps = {
Expand All @@ -23,21 +22,33 @@ export type BillboardProps = {
export const Billboard: ForwardRefComponent<BillboardProps, Group> = /* @__PURE__ */ React.forwardRef<
Group,
BillboardProps
>(function Billboard({ follow = true, lockX = false, lockY = false, lockZ = false, ...props }, ref) {
const localRef = React.useRef<Group>()
>(function Billboard({ children, follow = true, lockX = false, lockY = false, lockZ = false, ...props }, fref) {
const inner = React.useRef<Group>(null!)
const localRef = React.useRef<Group>(null!)
const q = new Quaternion()

useFrame(({ camera }) => {
if (!follow || !localRef.current) return

// save previous rotation in case we're locking an axis
const prevRotation = localRef.current.rotation.clone()

// always face the camera
camera.getWorldQuaternion(localRef.current.quaternion)
localRef.current.updateMatrix()
localRef.current.updateWorldMatrix(false, false)
localRef.current.getWorldQuaternion(q)
camera.getWorldQuaternion(inner.current.quaternion).premultiply(q.invert())

// readjust any axis that is locked
if (lockX) localRef.current.rotation.x = prevRotation.x
if (lockY) localRef.current.rotation.y = prevRotation.y
if (lockZ) localRef.current.rotation.z = prevRotation.z
})
return <group ref={mergeRefs([localRef, ref])} {...props} />

React.useImperativeHandle(fref, () => localRef.current, [])
return (
<group ref={localRef} matrixAutoUpdate={false} matrixWorldAutoUpdate={false} {...props}>
<group ref={inner}>{children}</group>
</group>
)
})

2 comments on commit 272b015

@vercel
Copy link

@vercel vercel bot commented on 272b015 Dec 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@neciszhang
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change caused a transformation exception in my game. I will have time to see what caused it.

Please sign in to comment.