在 Sphere 上应用图片的问题

Issue with applying a picture on Sphere

我在这里阅读了很多主题,用谷歌搜索,观看了 youtube...只是无法让我的 Sphere 获得纹理。 运行 此代码只显示白色球体但没有纹理...请帮助新手 <3

完整代码如下:

import { View as GraphicsView } from 'expo-graphics';
import ExpoTHREE, { THREE } from 'expo-three';
import React from 'react';

export default class App extends React.Component {
  componentWillMount() {
    THREE.suppressExpoWarnings();
  }

  render() {
    // Create an `ExpoGraphics.View` covering the whole screen, tell it to call our
    // `onContextCreate` function once it's initialized.
    return (
      <GraphicsView
        onContextCreate={this.onContextCreate}
        onRender={this.onRender}
      />
    );
  }

  // This is called by the `ExpoGraphics.View` once it's initialized

  onContextCreate = async ({
    gl,
    canvas,
    width,
    height,
    scale: pixelRatio,
  }) => {
    this.renderer = new ExpoTHREE.Renderer({ gl, pixelRatio, width, height });
    this.renderer.setClearColor(0x00cbff)
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(120, width / height, 0.1, 1000);
    this.camera.position.z = 5;
    const loader = new THREE.TextureLoader();
    const geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
    const material = new THREE.MeshPhongMaterial({map: loader.load('https://threejsfundamentals.org/threejs/resources/images/wall.jpg')});

    this.cube = new THREE.Mesh(geometry, material);
    this.scene.add(this.cube);

    this.scene.add(new THREE.AmbientLight(0x000000));

    const light = new THREE.DirectionalLight(0xffffff, 0.5);
    light.position.set(3, 3, 3);
    this.scene.add(light);
  };

  onRender = delta => {
    this.cube.rotation.x += 3.5 * delta;
    this.cube.rotation.y += 2 * delta;
    this.renderer.render(this.scene, this.camera);
  };
}

不确定这是否是一个卑鄙的要求,但我相信 expo 需要从本地商店而不是远程 URL 加载其资源。

首先,下载 wall.jpg 文件并将其存储在本地(在我的例子中,根目录中的文件夹名为 'assets'。

现在,您需要配置 expo 以将 jpg 文件添加到您的包中。在您的应用程序的根目录中打开 app.json 并更新或添加到 "packagerOpts" 以便包含 jpg:

    "packagerOpts": {
      "assetExts": ["jpg"]
    },

您可能还需要在应用的根目录中创建一个名为 "metro.config.js" 的文件,其中包含以下内容:

module.exports = {
  resolver: {
    assetExts: ["jpg"]
  }
}

现在您的打包程序已将 JPG 文件包含在您的 expo 应用程序包中,您可以使用 ExpoTHREE 的内置 loadAsync 函数来加载您的 jpg:

const texture = await ExpoTHREE.loadAsync(
  require('./assets/wall.jpg')
);
const geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
const material = new THREE.MeshPhongMaterial({map: texture});

通过这些更改,您的代码看起来对我有效。您可以使用相同的过程将不同类型的文件添加到您的包中并加载它们以便在 ExpoTHREE 中使用。只需将各种文件类型添加到您的 app.json 和 metro.config.js 中的数组中,它们将被捆绑以供您的应用程序使用。