Search code examples
graphicsthree.jsreact-three-fiber

How to get new coordinates after rotation in 3D at certain angle in terms of trigonometry, Just like given example in codesandbox


I need your help.

I know about rotation matrix and how it is used to get the new coordinates after rotating in certain angle. But I am not able to get how in below code new coordinates are being captured and cube is revolving around the imaginary circle.

I am using react three fiber - react library for using ThreeJS. If you don't know about this library, still you can figure it out if you are good in computer graphics and mathematics of it.

Live example - https://codesandbox.io/s/capra-christmas-forked-eukvyi

function Box() {
  const [ref, api] = useBox(() => ({ mass: 1, args: [1, 1, 1], position: [1, 1, 1], isKinematic: true }))
  useFrame((state) => {
    const t = state.clock.getElapsedTime() // get elapsed time within frame. if you new to react three fiber you can think it will get new increasing time after every sec. 
    api.position.set(Math.cos(2 * t ) * 10, Math.sin(20 ) * 5, Math.sin(20) + 1.5) // how this line of code specifying coordinates (x,y,z) in terms of trigonometry 
    api.rotation.set(Math.sin(t * 6), Math.cos(t * 6), Math.sin(t * 6))
  })
  return (
    <mesh ref={ref} castShadow receiveShadow position={[10, 0, 0]}>
      <boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
      <meshLambertMaterial attach="material" color="red" side={THREE.DoubleSide} />
    </mesh>
  )
}

Solution

  • in the code sandbox you referenced they are using the parametric equation of a circle to rotate an object around a given point, heres a nice visualization.

    https://www.mathopenref.com/coordparamcircle.html

    the idea is to change one axis based on cos(theta) and another based on sin(theta) *theta in this case being time

    api.position.set(Math.cos(2 * t) * 10, Math.sin(20 * t) * 5, Math.sin(20) + 1.5)
    

    it looks like in your code you are changing your cos function based on time but not your sin function. try using the snippet above. also the third axis in the code sandbox is just used to make the object move up and down a little as it rotates. You can look into the maths in the link above to get a better understanding of what is happening.