Remove perspective warping in react three fiber - three.js

I'm trying to make a sphere that follows my cursor. Most of it is done, however, the sphere severely warps on the edges of my screen.
Middle of screen:
Edge of screen:
I have the default camera (fov changed) setup but I feel like it's the wrong one
Canvas:
const Canvas: NextPage<CanvasProps> = ({ children }) => {
const camera = { fov: 60, near: 0.1, far: 1000, position: [0, 0, 5] }
return (
<ThreeCanvas className="bg-gray-900" camera={camera}>
{children}
<Mouse />
</ThreeCanvas>
)
}
Mouse.tsx:
const Mouse: NextPage<MouseProps> = ({}) => {
const [active, setActive] = useState(false)
const { viewport } = useThree()
const { scale } = useSpring({ scale: active ? 0.7 : 1 })
useEffect(() => {
if (active) {
setTimeout(() => setActive(false), 200)
}
}, [active])
const ref = useRef()
useFrame(({ mouse }) => {
const x = (mouse.x * viewport.width) / 2
const y = (mouse.y * viewport.height) / 2
if (typeof ref !== undefined) {
// #ts-ignore
ref!.current.position.set(x, y, 0)
// #ts-ignore
ref!.current.rotation.set(-y, x, 0)
}
})
return (
<>
<ambientLight />
<pointLight position={[10, 10, 10]} />
<animated.mesh scale={scale} onClick={() => setActive(!active)} ref={ref}>
<sphereGeometry args={[0.15, 32, 32]} />
<meshStandardMaterial color="beige" transparent />
</animated.mesh>
</>
)
}

Related

How to make smooth camera transition in react three fiber

Till now I have managed to achieve camera shifting from one place to another but it goes all of a sudden i want a animation or a smooth effect in between current and final camera point
function Rig({ children }) {
const outer = useRef(null)
const inner = useRef(null)
const [pos, setPos] = useState({
x: -12,
y: 20,
z: 34
})
const [type, setType] = useState('initial')
setTimeout(() => {
setType('third')
}, 5000)
useEffect(() => {}, [pos])
useFrame(({ camera, clock }) => {
if (type === 'initial') {
outer.current.position.y = THREE.MathUtils.lerp(outer.current.position.y, 0, 0.05)
inner.current.rotation.y = Math.sin(clock.getElapsedTime() / 8) * Math.PI
inner.current.position.z = 5 + -Math.sin(clock.getElapsedTime() / 2) * 10
inner.current.position.y = -5 + Math.sin(clock.getElapsedTime() / 2) * 2
}
if (type === 'final') {
camera.position.set(0, 20, 34)
}
})
return (
<group position={[0, -100, 0]} ref={outer}>
<group ref={inner}>{children}</group>
</group>
)
}
I read in the documentation this could be achieve through react spring or tween camera but i couldn't implement any of those
I use CameraControls npm i camera-controls, but don't know how to change transition speed
Example https://codesandbox.io/s/react-three-fiber-camera-controls-4jjor?file=/src/App.tsx

The model scale is too small when using in web application project

I downloaded this model from https://sketchfab.com/3d-models/dcb3a7d5b1ad4f948aa4945d6e378c8a , The model scale is appearing normal when open in Windows 3D Viewer, three.js glTF Viewer and Babylon.js View, but when load the model in three.js module, some model's scale is incorrect, for example.
three.js in Website
three.js glTF Viewer
Babylon.js Viewer
This model scale is correct, when open in another application, it scale correctly.
Model name : dog.glb
Source : https://github.com/craftzdog/craftzdog-homepage
three.js in Website
three.js glTF Viewer
Babylon.js Viewer
This model scale is incorrect and so tiny, but when open in another application, it scale correctly
Model name : แมวประเทศไทย
Source : https://sketchfab.com/3d-models/dcb3a7d5b1ad4f948aa4945d6e378c8a
Here is GLTF Loader Code
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
export function loadGLTFModel(
scene,
glbPath,
options = { receiveShadow: true, castShadow: true }
) {
const { receiveShadow, castShadow } = options
return new Promise((resolve, reject) => {
const loader = new GLTFLoader()
loader.load(
glbPath,
gltf => {
const obj = gltf.scene
obj.name = 'persian'
obj.position.x = 0
obj.position.y = 0
obj.receiveShadow = receiveShadow
obj.castShadow = castShadow
scene.add(obj)
obj.traverse(function (child) {
if (child.isMesh) {
child.castShadow = castShadow
child.receiveShadow = receiveShadow
}
})
resolve(obj)
},
undefined,
function (error) {
reject(error)
}
)
})
}
Here is Model Display Code
import { useState, useEffect, useRef, useCallback } from 'react'
import { Box, Spinner } from '#chakra-ui/react'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { loadGLTFModel } from '../lib/model'
function easeOutCirc(x) {
return Math.sqrt(1 - Math.pow(x - 1, 4))
}
const PersianCat = () => {
const refContainer = useRef()
const [loading, setLoading] = useState(true)
const [renderer, setRenderer] = useState()
const [_camera, setCamera] = useState()
const [target] = useState(new THREE.Vector3(-0.5, 1.2, 0))
const [initialCameraPosition] = useState(
new THREE.Vector3(
20 * Math.sin(0.2 * Math.PI),
10,
20 * Math.cos(0.2 * Math.PI)
)
)
const [scene] = useState(new THREE.Scene())
const [_controls, setControls] = useState()
// On component mount only one time.
/* eslint-disable react-hooks/exhaustive-deps */
useEffect(() => {
const { current: container } = refContainer
if (container && !renderer) {
const scW = container.clientWidth
const scH = container.clientHeight
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
})
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(scW, scH)
renderer.outputEncoding = THREE.sRGBEncoding
container.appendChild(renderer.domElement)
setRenderer(renderer)
// 640 -> 240
// 8 -> 6
const scale = scH * 0.005 + 4.8
const camera = new THREE.OrthographicCamera(
-scale,
scale,
scale,
-scale,
0.01,
50000
)
camera.position.copy(initialCameraPosition)
camera.lookAt(target)
setCamera(camera)
const ambientLight = new THREE.AmbientLight(0xcccccc, 1)
scene.add(ambientLight)
const controls = new OrbitControls(camera, renderer.domElement)
controls.autoRotate = true
controls.target = target
setControls(controls)
loadGLTFModel(scene, '/persian.glb', {
receiveShadow: false,
castShadow: false
}).then(() => {
animate()
setLoading(false)
})
let req = null
let frame = 0
const animate = () => {
req = requestAnimationFrame(animate)
frame = frame <= 100 ? frame + 1 : frame
if (frame <= 100) {
const p = initialCameraPosition
const rotSpeed = -easeOutCirc(frame / 120) * Math.PI * 20
camera.position.y = 10
camera.position.x =
p.x * Math.cos(rotSpeed) + p.z * Math.sin(rotSpeed)
camera.position.z =
p.z * Math.cos(rotSpeed) - p.x * Math.sin(rotSpeed)
camera.lookAt(target)
} else {
controls.update()
}
renderer.render(scene, camera)
}
return () => {
cancelAnimationFrame(req)
renderer.dispose()
}
}
}, [])
return (
<Box
ref={refContainer}
className="persian-cat"
m="auto"
at={['-20px', '-60px', '-120px']}
mb={['-40px', '-140px', '-200px']}
w={[280, 480, 640]}
h={[280, 480, 640]}
position="relative"
>
{loading && (
<Spinner
size="xl"
position="absolute"
left="50%"
top="50%"
ml="calc(0px - var(--spinner-size) / 2)"
mt="calc(0px - var(--spinner-size))"
/>
)}
</Box>
)
}
export default PersianCat

How to control movement of a person in react three fiber?

I want to create a game where I have to make my model controllable with keyboard input. I don't know what's the best way to do it and how to implement it properly.
We can implement this with cannon.js
Create a custom hook to listen to user's input.
const usePersonControls = () => {
const keys = {
KeyW: 'forward',
KeyS: 'backward',
KeyA: 'left',
KeyD: 'right',
Space: 'jump',
}
const moveFieldByKey = (key) => keys[key]
const [movement, setMovement] = useState({
forward: false,
backward: false,
left: false,
right: false,
jump: false,
})
useEffect(() => {
const handleKeyDown = (e) => {
setMovement((m) => ({ ...m, [moveFieldByKey(e.code)]: true }))
}
const handleKeyUp = (e) => {
setMovement((m) => ({ ...m, [moveFieldByKey(e.code)]: false }))
}
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keyup', handleKeyUp)
}
}, [])
return movement
}
Now use it like so,
const { forward, backward, left, right, jump } = usePersonControls()
Create a body for person in Cannon World.
const [mesh, api] = useSphere(() => ({
mass: 10,
position: [0, 1, 0],
type: 'Dynamic',
}))
Apply velocity to sphere body.
useFrame(() => {
// Calculating front/side movement ...
let frontVector = new Vector3(0,0,0);
let sideVector = new Vector3(0,0,0);
let direction = new Vector3(0,0,0);
frontVector.set(0, 0, Number(forward) - Number(backward))
sideVector.set(Number(right) - Number(left), 0, 0)
direction
.subVectors(frontVector, sideVector)
.normalize()
.multiplyScalar(SPEED)
api.velocity.set(direction.x, 0, direction.z)
})
Now our sphere body is able to move with user's input in Cannon World, so now just update your player model in fiber using sphere's position on each frame, like so
// Setting person model position to sphere body position ...
useFrame(() => {
...
mesh.current.getWorldPosition(playerModelReference.current.position)
})
Sorry for long explanation, hope you find it helpful.
look here for details on the where does frontVector gets defined
Line 24:9: 'frontVector' is not defined
How to make character to move around 3D world in React Three Fiber?
import React from "react";
import { useSphere } from "#react-three/cannon";
import { useThree, useFrame } from "#react-three/fiber";
import { useKeyboardControls } from "../hooks/useKeyboardControls";
import { Vector3 } from "three";
const SPEED = 6;
export function Person(props) {
const { camera } = useThree();
const { moveForward, moveBackward, moveLeft, moveRight } =
useKeyboardControls();
const [ref, api] = useSphere(() => ({
mass: 1,
type: "Dynamic",
...props,
}));
const velocity = React.useRef([0, 0, 0]);
React.useEffect(() => {
api.velocity.subscribe((v) => (velocity.current = v));
}, [api.velocity]);
useFrame(() => {
camera.position.copy(ref.current.position);
const direction = new Vector3();
const frontVector = new Vector3(
0,
0,
Number(moveBackward) - Number(moveForward)
);
const sideVector = new Vector3(
Number(moveLeft) - Number(moveRight),
0,
0
);
direction
.subVectors(frontVector, sideVector)
.normalize()
.multiplyScalar(SPEED)
.applyEuler(camera.rotation);
api.velocity.set(direction.x, velocity.current[1], direction.z);
});
return (
<>
<mesh ref={ref} />
</>
);
}

Camera rotation and OrbitControls in react-three/fiber

I am trying to create a scene with react-three/fiber and react-three/drei. I want to use a PerspectiveCamera and be able to pan/zoom/rotate with the mouse, but I am also trying to add some buttons that can update the camera position and target in order to have different views (eg. top view, bottom view, side view, etc). I have achieved the latter part and my buttons seem to be working as I update the target x,y,z and position x,y,z using props.
The only problem is that the camera is not responding to the mouse so I only get a fixed camera position and target.
I have included all the scene codes below.
import React,{ useRef, useState, useEffect} from 'react'
import * as THREE from 'three';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { PerspectiveCamera, Icosahedron, OrbitControls } from '#react-three/drei'
import { Canvas, useThree } from "#react-three/fiber";
function VisualizationComponent(props) {
const width = window.innerWidth;
const height = window.innerHeight;
const [controls, setControls] = useState(null);
const [threeState, setThreeState] = useState(null);
const [treeStateInitialized, setThreeStateInitialized] = useState(false);
useEffect(()=>{
if(threeState){
_.forOwn(props.objects, (value, key) => {
threeState.scene.current.add(value);
});
}
return () => {
if(controls) controls.dispose();
}
},[])
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
const { objects } = props
const prevState = usePrevious({objects});
const mainCamera = useRef();
useEffect(() => {
if(!threeState) return;
if (
!treeStateInitialized ||
shouldUpdateObjects(props.objects, prevState.objects)
) {
setThreeStateInitialized(true);
garbageCollectOldObjects();
addDefaultObjects();
_.forOwn(props.objects, (value, key) => {
threeState.scene.add(value);
});
}
})
const addDefaultObjects = () => {
if (threeState) {
var hemiLight = new THREE.HemisphereLight( 0xffffbb, 0x080820, 0.2 );
hemiLight.position.set( 0, 0, 1 );
threeState.scene.add( hemiLight );
}
}
const garbageCollectOldObjects = () => {
while (threeState && threeState.scene.children.length) {
const oldObject = threeState.scene.children[0];
oldObject.traverse((child) => {
if (child.geometry) {
child.geometry?.dispose();
if(child.material && Array.isArray(child.material)){
child.material.forEach(d => d.dispose());
}else{
child.material?.dispose();
}
}
});
threeState.scene.remove(oldObject);
}
}
const shouldUpdateObjects = (currentObjects,nextObjects) => {
const result = false;
let currentDigest = 1;
let nextDigest = 1;
_.forIn(currentObjects, (value, key) => {
currentDigest *= value.id;
});
_.forIn(nextObjects, (value, key) => {
nextDigest *= value.id;
});
return currentDigest !== nextDigest;
}
const hasAncestorWhichDisablesThreeJs = (element) => {
if (!element) return false;
let isEditable = false;
for (let i = 0; i < element.classList.length; i++) {
if (element.classList[i] === 'disable-threejs-controls') {
isEditable = true;
}
}
return isEditable ||
hasAncestorWhichDisablesThreeJs(element.parentElement);
}
const initializeScene = (state) => {
setThreeState(state);
addDefaultObjects();
}
return (
<div
id="threejs-controllers-div"
className='threejs-container'
onMouseOver={ (e) => {
const target = e.target;
if (!target || !controls) return true;
if (hasAncestorWhichDisablesThreeJs(target)) {
controls.enabled = false;
} else {
controls.enabled = true;
}
} }
>
<Canvas
className='threejs'
onCreated={ (state) => {initializeScene(state)}}
shadows={true}
gl={
{
'shadowMap.enabled' : true,
'alpha' : true
}
}
>
<PerspectiveCamera
makeDefault
ref={mainCamera}
position-x={props.cameraX || 0}
position-y={props.cameraY || -20}
position-z={props.cameraZ || 20}
up={[0, 0, 1]}
fov={ 15 }
aspect={ width / height }
near={ 1 }
far={ 10000 }
visible={false}
controls={controls}
/>
<OrbitControls
ref={controls}
camera={mainCamera.current}
domElement={document.getElementById("threejs-controllers-div")}
enabled={true}
enablePan={true}
enableZoom={true}
enableRotate={true}
target-x={props.targetX || 0}
target-y={props.targetY || 0}
target-z={props.targetZ || 0}
/>
</Canvas>
<div className='threejs-react-container'>
{ props.children }
</div>
</div>
)
}
VisualizationComponent.propTypes = {
children: PropTypes.node.isRequired,
objects: PropTypes.object.isRequired,
cameraX: PropTypes.number,
cameraY: PropTypes.number,
cameraZ: PropTypes.number,
targetX: PropTypes.number,
targetY: PropTypes.number,
targetZ: PropTypes.number,
};
export default withRouter(VisualizationComponent);

d3 zoom behavior in React Native

In React Native I draw my charts with d3 and ART libraries.
export default class DevTest extends React.Component {
static defaultProps = {
width: 300,
height: 150,
}
mainScaleX = d3Scale.scaleTime()
.domain(d3Array.extent(chartDataTo, data => data.date))
.range([0, this.props.width])
mainScaleY = d3Scale.scaleLinear()
.domain(d3Array.extent(chartDataTo, data => data.value))
.range([this.props.height, 0])
rawChartValue = d3Shape.line()
.x(data => this.mainScaleX(data.date))
.y(data => this.mainScaleY(data.value))
render(){
return (
<View>
<Surface width = {this.props.width} height = {this.props.height}>
<Group x = {0} y = {0}>
<Shape
d = {this.rawChartValue(chartData)}
stroke = "#000"
strokeWidth = {1}
/>
</Group>
</Surface>
</View>
)
}
}
Is there any way to implement d3 svg-like zoom behavior, but without DOM mutation. For example, using some d3 pure functions with just x and y values as input to rescale mainScaleX and mainScaleY?
You can use PanResponder from react-native and zoomIdentity from d3-zoom for that purpose.
Code example looks sometihng like this
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onPanResponderMove: (event, { dx, dy }) => {
const zoomIdentity = d3Zoom.zoomIdentity.translate(dx, dy)
this._onDrag(zoomIdentity)
},
});
}
_onDrag(zoomIdentity){
this.setState({
rescaledX: zoomIdentity.rescaleX(this.state.mainScaleX),
rescaledY: zoomIdentity.rescaleY(this.state.mainScaleY)
})
}
And you pass your rescaled{X, Y} to a chart component
render(){
return (
<View {...this._panResponder.panHandlers}>
<Component
{...this.props}
scaleX = {this.state.rescaledX}
scaleY = {this.state.rescaledY}
/>
</View>
)
}

Resources