Skip to content

Commit

Permalink
fix(cannon-worker-api): support rotation and quaternion, prefer quate…
Browse files Browse the repository at this point in the history
…rnion if both provided
  • Loading branch information
isaac-mason committed Aug 5, 2023
1 parent acffe39 commit 67e37e6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
3 changes: 3 additions & 0 deletions packages/cannon-worker-api/src/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ export type BodyProps<T extends any[] = unknown[]> = Partial<AtomicProps> &
onCollide?: (e: CollideEvent) => void
onCollideBegin?: (e: CollideBeginEvent) => void
onCollideEnd?: (e: CollideEndEvent) => void
/**
* Quaternion is preferred over rotation if both are provided
*/
quaternion?: Quad
rotation?: Triplet
type?: 'Dynamic' | 'Static' | 'Kinematic'
Expand Down
29 changes: 19 additions & 10 deletions packages/cannon-worker-api/src/props-to-body.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ function createShape(type, args) {
}
}

/**
* @param {THREE.Quaternion} target
* @param {{ rotation?: THREE.Vector3Tuple quaternion?: THREE.Vector4Tuple }} props
* @returns {THREE.Quaternion}
*/
const setQuaternion = (target, { quaternion, rotation }) => {
if (quaternion) {
target.set(...quaternion)
} else if (rotation) {
target.setFromEuler(...rotation)
}

return target
}

/**
* @function
* @param {Object} options
Expand All @@ -70,8 +85,8 @@ export const propsToBody = (options) => {
material,
onCollide,
position = [0, 0, 0],
rotation = [0, 0, 0],
quaternion = [0, 0, 0, 1],
rotation,
quaternion,
shapes,
type: bodyType,
velocity = [0, 0, 0],
Expand All @@ -95,11 +110,7 @@ export const propsToBody = (options) => {
const shapeBody = body.addShape(
createShape(type, args),
position ? new Vec3(...position) : undefined,
quaternion
? new Quaternion.set(...quaternion)
: rotation
? new Quaternion().setFromEuler(...rotation)
: undefined,
setQuaternion(new Quaternion(0, 0, 0, 1), { quaternion, rotation }),
)
if (material) shapeBody.material = createMaterial(material)
Object.assign(shapeBody, extra)
Expand All @@ -113,9 +124,7 @@ export const propsToBody = (options) => {
body.angularVelocity.set(angularVelocity[0], angularVelocity[1], angularVelocity[2])
body.linearFactor.set(linearFactor[0], linearFactor[1], linearFactor[2])
body.angularFactor.set(angularFactor[0], angularFactor[1], angularFactor[2])

if (quaternion) body.quaternion.set(quaternion[0], quaternion[1], quaternion[2], quaternion[3])
else body.quaternion.setFromEuler(rotation[0], rotation[1], rotation[2])
setQuaternion(body.quaternion, { quaternion, rotation })

return body
}

0 comments on commit 67e37e6

Please sign in to comment.