当我尝试使用 cannon.js 时,屏幕会变成空白

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

我尝试了很多方法,但我无法让 cannon.js 在我的代码中工作。当我试图创造一个世界时,它只是一片空白,请帮忙。我找不到任何链接或方法来让它工作。我是一名新编码员,我不太喜欢使用库,我想进一步了解它们。我尝试过将脚本与 src 一起使用,并且尝试了很多链接。我需要在没有其他文件的情况下实现它。每当 CANNON 被引用时,代码就会中断。我不知道是否有某种我不知道的方式或者我只是缺少一些东西。

我的代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My first three.js app</title>
    <style>
      body { margin: 0; }
    </style>
    <script src="https://threejs.org/build/three.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js"></script>
    <script type="importmap">
      {
        "imports": {
          "three": "https://unpkg.com/[email protected]/build/three.module.js",
          "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/",
          "dat.gui": "https://unpkg.com/[email protected]/build/dat.gui.module.js",
          "cannon-es": "/cannon-es"
        }
      }
    </script>
  </head>
  <body>
    <script type="module">
      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
      import { MMDPhysics } from "three/addons/animation/MMDPhysics.js";
      import { MMDLoader } from "three/addons/loaders/MMDLoader.js";
      import { PointerLockControls } from "three/addons/controls/PointerLockControls.js";
      import CannonUtils from '/utils/cannonUtils.js'
      import CannonDebugRenderer from '/utils/cannonDebugRenderer.js'
      const loader = new MMDLoader();

      //import * as CANNON from "cannon-es";

      import * as CANNON from "cannon-es";

    const world = new CANNON.World();

      function render() {
        const delta = clock.getDelta();
        animate(delta); // update bones
        renderer.render(scene, camera);
      }

      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );

     

      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      const concreteTexture = new THREE.TextureLoader().load(
        "https://threejsfundamentals.org/threejs/resources/images/wall.jpg"
      );
      const controls = new PointerLockControls(camera, document.body);

      const geometry = new THREE.BoxGeometry(
        1,
        1,
        1
      ); /*new THREE.TorusKnotGeometry(
          1,
          0.125,
          100,
          18
        );*/
      const material = new THREE.MeshPhysicalMaterial({
        color: 0x00ff00,
        map: concreteTexture,
        clearcoat: 0.1,
      });
      
      

      const smateral = new THREE.ShadowMaterial({ opacity: 0.5 });
      material.clearcoat = 1.0;
      material.clearcoatRoughness = 0.2;
      const cube = new THREE.Mesh(geometry, material);
      const cubes = new THREE.Mesh(geometry, smateral);
      cube.position.y = 2;
      cubes.position.y = 2;
      cube.castShadow = true;
      cubes.receiveShadow = true;
      //const cubePy = new MMDPhysics(cube,geometry);
      scene.add(cube);
      scene.add(cubes);
      

      const geometry2 = new THREE.SphereGeometry(
        1,
        32,
        16
      ); /*new THREE.TorusKnotGeometry(
          1,
          0.125,
          100,
          18
        )*/
      const material2 = new THREE.MeshPhysicalMaterial({
        color: 0x00ff00,
        map: concreteTexture,
      });
      material2.clearcoat = 1.0;
      material2.clearcoatRoughness = 0.2;
      const cube2 = new THREE.Mesh(geometry2, material2);
      cube2.position.y = 2;
      cube2.castShadow = true;
      cube2.receiveShadow = true;
      cube2.position.z = 10;
      scene.add(cube2);

      const groundMaterial = new THREE.MeshPhysicalMaterial({
        map: concreteTexture,
        clearcoat: 1,
        clearcoatRoughness: 1,
        metalness: 0.9,
      });

      const sadowM = new THREE.ShadowMaterial({ opacity: 0.5 });
      const groundGeometry = new THREE.PlaneGeometry(20, 20, 100, 100);
      const shadowG = new THREE.Mesh(groundGeometry, sadowM);
      const ground = new THREE.Mesh(groundGeometry, groundMaterial);
      ground.rotation.x = -Math.PI / 2;
      shadowG.rotation.x = -Math.PI / 2;

      shadowG.receiveShadow = true;
      scene.add(ground);
      scene.add(shadowG);

     
      // Set background color to blue
      scene.background = new THREE.Color(0x87ceeb); // Sky Blue

      // Create a directional light
      const light = new THREE.DirectionalLight(0xffffff, 1);
      light.position.set(0, 15, 5);
      light.castShadow = true;
      camera.castShadow = true;

      const helper = new THREE.CameraHelper(light.shadow.camera);

      scene.add(helper);

      // Adjust shadow parameters
      light.shadow.camera.near = 0.1;
      light.shadow.camera.far = 40; // Increased far value
      light.shadow.mapSize.width = 1025;
      light.shadow.mapSize.height = 1025;
      light.shadow.radius = 4;

      scene.add(light);

      // Enable shadows
      renderer.shadowMap.enabled = true;

      light.shadow.camera.left = -10;
      light.shadow.camera.right = 10;
      light.shadow.camera.top = 10;
      light.shadow.camera.bottom = -10;
      light.shadow.bias = -0.002;

      camera.position.y = 1;

      var keys = {};
      var code = {};
      window.addEventListener("keydown", function (ev) {
        keys[ev.key] = true;
      });
      window.addEventListener("keyup", function (ev) {
        keys[ev.key] = false;
      });

      const moveVector = new THREE.Vector3();

      camera.rotation.order = "YXZ";

      function go() {
        if (keys.w) moveVector.z -= 0.1;
        if (keys.s) moveVector.z += 0.1;
        if (keys.a) moveVector.x -= 0.1;
        if (keys.d) moveVector.x += 0.1;
        if (keys.c) moveVector.y -= 0.1;
        if (keys.v) moveVector.y += 0.1;
        if (keys.m) controls.lock();

        if (keys.ArrowRight) camera.rotation.y -= 0.05;
        if (keys.ArrowLeft) camera.rotation.y += 0.05;
        if (keys.ArrowUp) camera.rotation.x += 0.05;
        if (keys.ArrowDown) camera.rotation.x -= 0.05;

        moveVector.multiplyScalar(0.6);
        camera.translateX(moveVector.x);
        camera.translateZ(moveVector.z);
        camera.translateY(moveVector.y);

        cube2.position.x = camera.position.x;
        cube2.position.y = camera.position.y;
        cube2.position.z = camera.position.z;

        
      }

      function animate() {
        requestAnimationFrame(animate);
        go();
        renderer.render(scene, camera);
      }

      animate();
    </script>
  </body>
</html>

。 我希望立方体具有可用的 cannon.js 物理特性并且能够完全实现。

javascript html three.js cannon.js
1个回答
0
投票

试试这个方法

<script type="importmap">
  {
    "imports": {
      "three": "https://unpkg.com/[email protected]/build/three.module.js",
      "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/",
      "cannon-es": "https://cdn.jsdelivr.net/npm/[email protected]/dist/cannon-es.min.js"
    }
  }
</script>

<script type="module">
  import * as THREE from "three";
  import { OrbitControls } from "three/addons/controls/OrbitControls.js";
  import { Clock } from "three";
  import * as CANNON from "cannon-es";

const clock = new Clock();
const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);

const physicsMaterial = new CANNON.Material();
const physicsContactMaterial = new CANNON.ContactMaterial(
  physicsMaterial,
  physicsMaterial,
  { friction: 0.0, restitution: 0.5 }
);
world.addContactMaterial(physicsContactMaterial);

function createCannonBox(size, position) {
  const shape = new CANNON.Box(
    new CANNON.Vec3(size.x / 2, size.y / 2, size.z / 2)
  );
  const body = new CANNON.Body({ mass: 1, material: physicsMaterial });
  body.addShape(shape);
  body.position.copy(position);
  world.addBody(body);
  return body;
}

const groundShape = new CANNON.Plane();
const groundBody = new CANNON.Body({
  mass: 0,
  shape: groundShape,
  material: physicsMaterial,
});
groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(groundBody);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.z = 3;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const concreteTexture = new THREE.TextureLoader().load(
  "https://threejsfundamentals.org/threejs/resources/images/wall.jpg"
);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshPhysicalMaterial({
  color: 0x00ff00,
  map: concreteTexture,
  clearcoat: 0.1,
});

const cube = new THREE.Mesh(geometry, material);
cube.castShadow = true;
scene.add(cube);

const cubeBody = createCannonBox(
  new THREE.Vector3(1, 1, 1),
  new CANNON.Vec3(0, 2, 0)
);

const groundMaterial = new THREE.MeshPhysicalMaterial({
  map: concreteTexture,
  clearcoat: 1,
  clearcoatRoughness: 1,
  metalness: 0.9,
});

const groundGeometry = new THREE.PlaneGeometry(20, 20, 100, 100);
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

scene.background = new THREE.Color(0x87ceeb);

const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 15, 5);
light.castShadow = true;
scene.add(light);

light.shadow.camera.near = 0.1;
light.shadow.camera.far = 40;
light.shadow.mapSize.width = 1025;
light.shadow.mapSize.height = 1025;
light.shadow.radius = 4;

renderer.shadowMap.enabled = true;

light.shadow.camera.left = -10;
light.shadow.camera.right = 10;
light.shadow.camera.top = 10;
light.shadow.camera.bottom = -10;
light.shadow.bias = -0.002;

camera.position.y = 1;

var keys = {};
window.addEventListener("keydown", function (ev) {
  keys[ev.key] = true;
});
window.addEventListener("keyup", function (ev) {
  keys[ev.key] = false;
});

const moveVector = new THREE.Vector3();

camera.rotation.order = "YXZ";

const initialCubePosition = cube.position.clone();

function resetCubePosition() {
  cubeBody.position.copy(new CANNON.Vec3(0, 2, 0));
  cube.position.copy(initialCubePosition);
  cubeBody.velocity.set(0, 0, 0);
}

const resetInterval = 2.0;
let lastResetTime = clock.elapsedTime;

function go() {
  if (keys.w) moveVector.z -= 0.1;
  if (keys.s) moveVector.z += 0.1;
  if (keys.a) moveVector.x -= 0.1;
  if (keys.d) moveVector.x += 0.1;
  if (keys.c) moveVector.y -= 0.1;
  if (keys.v) moveVector.y += 0.1;

  moveVector.multiplyScalar(0.6);
  camera.translateX(moveVector.x);
  camera.translateZ(moveVector.z);
  camera.translateY(moveVector.y);

  cube.position.copy(cubeBody.position);

  if (clock.elapsedTime - lastResetTime >= resetInterval) {
    resetCubePosition();
    lastResetTime = clock.elapsedTime;
  }
}

function animate() {
  const delta = clock.getDelta();
  world.step(delta);
  go();
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
}

animate();
</script>

© www.soinside.com 2019 - 2024. All rights reserved.