Updating objects x,y,z axis when position changes

Im trying to achieve the movement of a boat using r3f and rapier, so far, i could only make the boat go forward(x) or backwards(-x), and when i set a new rotation to the boat, the axis stays the same, so when the boat turns the movements is still set to go to the original x axis

Im thinking to simulate the steering, rotating on y and keep moving forward, but i cant seem to achieve that effect

this is what ive been doing so far

    setBouyancy(frontRightRef, state.clock.elapsedTime);
    setBouyancy(frontLeftRef, state.clock.elapsedTime);
    setBouyancy(botRightRef, state.clock.elapsedTime);
    setBouyancy(botLeftRef, state.clock.elapsedTime);

    // Controls
    const { forward, backward, leftward, rightward } = getKeys();
    const impulse = { x: 0, y: 0, z: 0 };
    const torque = { x: 0, y: 0, z: 0 };

    const impulseStrength = 0.6;
    const torqueStrength = 0.6;
    if (forward) {
      impulse.x += impulseStrength;
      torque.x -= torqueStrength;

      if (rightward) {
        torque.y -= torqueStrength * 2;
      }
      if (leftward) {
        torque.y += torqueStrength * 2;
      }
    }

    if (PlayerRef.current) {
      PlayerRef.current.applyImpulseAtPoint(
        impulse,
        {
          x: PlayerRef.current.translation().x - 4,
          y: PlayerRef.current.translation().y,
          z: PlayerRef.current.translation().z,
        },
        false
      );
      PlayerRef.current.applyTorqueImpulse(torque);
    }
  });

where PlayerRef is a reference to a RigidBody

As per docs - applyImpulseAtPoint uses world-space coordinates. To move the boat in the direction it’s facing, either convert local direction vector you’re using to world coordinates, or just fetch the direction instead:

const impulse = new Three.Vector3();

boatModelRef.current.getWorldDirection(impulse); // NOTE Make sure you're fetching the direction from your Mesh, not from the RigidBody

impulse.multiplyScalar(0.6);

rigidBodyRef.current. applyImpulseAtPoint(
  impulse,
  { /* x: ..., y: ..., z: ... */ },
  false
);
2 Likes

This is brilliant, thank you so much