首页 > 解决方案 > 使用 expo 和三、js 渲染动画对象与 React Native

问题描述

我的目标是在 react-native 应用程序中显示一个旋转的立方体。我可以使用此代码显示立方体,但每当我取消注释旋转时,它就会消失。渲染器有什么用吗?

我使用零食,立方体仅在“Web”视图中可见,而不是在 iOS 或 Android 中。

import * as React from 'react';
import { View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

import { GLView } from 'expo-gl';
import { THREE } from 'expo-three';
import ExpoTHREE from 'expo-three';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this._onGLContextCreate = this._onGLContextCreate.bind(this);
    this.animate = this.animate.bind(this);
  }

  _onGLContextCreate = async gl => {
    this.scene = new THREE.Scene();
    this.camera = new THREE.Camera(
      75,
      gl.drawingBufferWidth / gl.drawingBufferHeight,
      0.1,
      1000
    );
    this.scene.add(this.camera);
    this.renderer = new ExpoTHREE.Renderer({ gl });
    this.geometry = new THREE.BoxGeometry(1, 1, 1);
    this.material = new THREE.MeshBasicMaterial({ color: 0xff0f00 });
    this.obj = new THREE.Mesh(this.geometry, this.material);
    this.edges = new THREE.EdgesGeometry(this.geometry);
    this.line = new THREE.LineSegments(
      this.edges,
      new THREE.LineBasicMaterial({ color: 0xffffff })
    );

    this.scene.add(this.line);
    this.scene.add(this.obj);
    this.animate();
  };

  animate = () => {
    requestAnimationFrame(this.animate);
    //this.geometry.rotation.x += 0.01;
    //this.geometry.rotation.y += 0.01;
    this.renderer.render(this.scene, this.camera);
  };

  render() {
    return (
      <View style={styles.container}>
        <GLView
          style={{ width: 300, height: 300 }}
          onContextCreate={this._onGLContextCreate}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

代码主要改编自https://medium.com/@zohayb1996/using-expo-and-three-js-with-react-native-4bcb353b222e

谢谢

标签: react-nativethree.jsexpo

解决方案


在 Three.js 中,您不旋转 a Geometry,而是旋转Mesh. 只需更新您的动画功能即可使用:

    this.obj.rotation.x += 0.01;
    this.obj.rotation.y += 0.01;

推荐阅读