如何控制立方体的移动?

问题描述 投票:0回答:1

我正在使用 3D (Three.js) 和物理 (Rapier),我想用方向键像汽车一样控制盒子的运动,但我很难用物理将运动固定在正确的方向。

这是一个代码示例https://codesandbox.io/s/q-stackoverflow-9j4sf1

我需要在里面插入什么

useFrame

useFrame

useFrame((state, delta) => {
if (ref.current) {
  const box = ref.current;
  /// what i should insert in this area
  // w/ArrpUP click
  if (controllers.forward.isPress) {
  //  What do I need to insert so that the box moves forward
  }
  // s/ArrpDown click
  if (controllers.backward.isPress) {
 //  What do I need to insert so that the box moves backward
  }
  // L/ArrpLeft click
  if (controllers.left.isPress) {
    //  What do I need to insert so that the box rotate left
  }
  // R/ArrpRight click
  if (controllers.right.isPress) {
     //  What do I need to insert so that the box rotate right
  }
}});
reactjs three.js physics react-fiber rapier
1个回答
0
投票

运动学角色控制器是一种更高级别的工具,它将发出适当的光线投射和形状投射,以根据障碍物调整用户定义的轨迹。 角色控制器指南

使用 DynamicRayCastVehicleController 类进行更真实的车辆模拟:DynamicRayCastVehicleController

这是使用

useFrame
循环函数的字符控制器的基本 JS 示例。您可能需要将
Cuboid
替换为
Capsule
以获得更平滑的结果。

// Create a basic world with all your obstacles
let world = new RAPIER.World({ x: 0.0, y: -9.81, z: 0.0 });

// Initialize your character rigid body and collider
let rigidBodyDesc = new RAPIER.RigidBodyDesc(RAPIER.RigidBodyType['KinematicPositionBased']);
let rigidBody = world.createRigidBody(rigidBodyDesc);
let colliderDesc = new RAPIER.ColliderDesc(RAPIER.Cuboid(0.5, 0.5, 0.5));
let collider = world.createCollider(colliderDesc, rigidBody);

// Initialize your character controller and conditions
let characterController = world.createCharacterController(0.01);
let velocity = new THREE.Vector3();
let movement = new THREE.Vector3();
let nextTranslation = new THREE.Vector3();
let speed = 5;

// Define your loop function
useFrame((state, delta) => {
if (ref.current) {
  // Simulate gravity
  velocity.y -= delta;

  // Simulate movement damping
  velocity.z *= 0.5;
  velocity.x *= 0.5;

  // Update velocity from keyboard input
  if (controllers.forward.isPress) velocity.z -= delta * speed;
  if (controllers.backward.isPress) velocity.z += delta * speed;
  if (controllers.left.isPress) velocity.x -= delta * speed;
  if (controllers.right.isPress) velocity.x += delta * speed;

  // Calculate collider movement
  controller.computeColliderMovement(collider, velocity);

  // (optional) Check collisions
  for (var i = 0; i < controller.numComputedCollisions(); i++) {
    let collision = controller.computedCollision(i);
  }

  // Calculate next translation from computed movement
  movement.copy(controller.computedMovement());
  nextTranslation.copy(rigidBody.translation());
  nextTranslation.add(movement);
  rigidBody.setNextKinematicTranslation(nextTranslation);
}});
© www.soinside.com 2019 - 2024. All rights reserved.