嗨,我开始用 Three.js 为我和我的朋友们制作一个小游戏。我观看了许多有关如何导入 .gltf 和 .glb 文件的教程。我使用包裹捆绑器和命令: npx Parcel ./src/index.html 开始我的项目。我已经寻找答案大约两个月了,但找不到可行的解决方案。 我的代码是
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
new GLTFLoader().load( new URL( 'terrain.glb', import.meta.url ), gltf => {
let model = gltf.scene;
model.position.y += 0.48;
scene.add(model);
});
我的 HTML 是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Car Game</title>
<style>
body {
margin: 0
}
</style>
</head>
<body>
<script src="./js/scripts.js" type="module"></script>
</body>
</html>
安装三个我使用:npm install 3 并安装我使用的 Parcel: npm install Parcel-bundler --save-dev
当我运行它时,屏幕不显示任何内容,并显示错误: scripts.cd665a19.js:42930未捕获的语法错误:无法在模块外部使用“import.meta”(位于scripts.cd665a19.js:42930:65)
我也这样尝试过
const loader = new GLTFLoader();
loader.load('terrain.glb', (gltf) => {
let model = gltf.scene;
model.position.y += 0.48;
scene.add(model);
});
但是当我运行它时,它并没有显示 3D 对象。该错误表明脚本标签:“<" is missing as far as i know that means that the object is seen as an Html file.
我还尝试从我的index.html文件中删除type =“module”标签,因为parcel显示了有关模块类型的错误,但没有任何改变。
我真的不知道更多了,我只有半年的 Three.js 经验和大约一年的 js Web 开发经验。如果我忘记了什么,请原谅,这是我在 stackoverflow 上的第一次探索,我的英语可能不是最好的,因为我来自德国,而且还只有 14 岁。 感谢您提前提供帮助:)
找到解决方案。
你需要像这样升级到parcel 2:npm install -D Parcel
因为parcel 2支持type="module"
然后你必须像这样导入你的.glb:
var url = new URL( 'terrain.glb', import.meta.url );
url = "" + url;
new GLTFLoader().load( url , gltf => {...});