Перетащите объекты в реагировать и Three.js - PullRequest
0 голосов
/ 09 июня 2019

Я пытался реализовать простое решение для перетаскивания в React и Three.js. Я добавил объекты вручную на плоскость и попытался перетащить их на план вдоль направления Y и Z.

В интернете очень мало примеров перетаскивания в React, и, похоже, ему нужен еще один Node-модуль. Я потратил пару часов, чтобы понять это.

Я перешел по этой ссылке https://codepen.io/kaolay/pen/bqKjVz,, но это сложно без комментариев.

import React, { Component } from 'react';
import * as THREE from 'three';
import NavBar from "./navbar.js";
import DragControls from 'drag-controls'
import {Button, Row, Col, Container} from "react-bootstrap";
const OrbitControls = require("three-orbit-controls")(THREE);
var raycaster = new THREE.Raycaster();
var OBJLoader = require('three-obj-loader');
var mouse = new THREE.Vector2();
OBJLoader(THREE);

export default class ThreeEntryPoint extends Component {
  constructor(){
    super();
    this.camera = "";
    this.scene  = "";
    this.renderer = "";
    this.world = "";
    this.ground = "";
    this.controls = "";
    this.container = "";
    this.state ={
      toggle: false,
      currentSandBoxState:""
    };
    this.itemList = [];
    this.lastAddedXPosition = 0;
    this.lastAddedZPosition = 0;
    this.selectedObject= "";
    this.offset = new THREE.Vector3();
  }


  setSandboxState = (e) => {
    console.log(e);
    this.setState({currentSandBoxState : e});
  }


  addTree = (x, z) => {
    this.THREE = THREE;
    var objLoader = new this.THREE.OBJLoader()
    this.setState({toggle: !this.state.toggle}) ;
    var this_ = this;

    objLoader.load('https://swamp-back.s3.eu-central-1.amazonaws.com/objects/lowpolytree.obj', function(object){
      object.position.y = 4;
      object.position.z = z + this_.lastAddedZPosition;
      object.position.x = x + this_.lastAddedXPosition;
      this_.lastAddedXPosition++;
      this_.lastAddedZPosition++;
      object.scale.set(2, 2, 2);
      this_.scene.add(object);
    },function(xhr) {
      }, function(error) {
        console.log(error);
    });
  }


  setCamera = (camera) => {
    camera.position.z = 100;
        camera.position.y = 30;
    camera.lookAt( new THREE.Vector3(0,0,0) );
    camera.add(new THREE.PointLight(0xffffff,0.7))
  }



  componentDidMount(  ) {
    this.Three = THREE;
    var container_ = document.getElementById("container-canvas");
    this.contaier = container_;
    const width  = window.innerWidth - 300;
    const height = window.innerHeight - 200;

    this.scene    = new THREE.Scene();
    this.camera   = new THREE.PerspectiveCamera( 45, width/height, 10, 1000 );
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setClearColor(0xfffffff);
    this.controls = new OrbitControls(this.camera, this.canvas);
    this.controls.target.set(0, 5, 0);
    this.controls.rotateSpeed = 1.0;
    this.controls.zoomSpeed   = 1.2;
    this.controls.panSpeed    = 0.8;

    this.renderer.setSize( width, height );
    container_.appendChild( this.renderer.domElement );

    var geometry     = new THREE.BoxGeometry( 250, 1, 40 );
    var material     = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    var cube         = new THREE.Mesh( geometry, material );
    var ambientLight = new THREE.AmbientLight( 0x0f0f0f );
    this.world        = new THREE.Object3D();


    this.ground = new THREE.Mesh(
            new THREE.BoxGeometry(100,1,40),
            new THREE.MeshLambertMaterial( {color:"green"})
        );

        this.ground.position.y = 0 // top of base lies in the plane y = -5;
    this.scene.add( this.world );

    let this_ = this;
    var animate = function () {
      requestAnimationFrame( animate );
      this_.controls.update();
      this_.renderer.render( this_.scene, this_.camera );
    };

    this.addTree(10, 11);
    this.scene.add(this.ground);
    this.scene.add( ambientLight );
    this.scene.add(new THREE.DirectionalLight(0xffffff,0.5));
    this.setCamera(this.camera);

    animate();
  }


  render(){
    return (
      <Container>
        <NavBar passState={this.setSandboxState}/>
          <Row id="container-canvas" style={{display:"flex", alignItems:"center", justifyContent:"center"}}>
        </Row>
      </Container>
    );
  }
};

Я установил минимальный код для рендеринга макета и добавления к нему одного объекта. Я много пытался найти модуль узла для управления захватом, но не смог найти ни одного

Может ли кто-нибудь предоставить простое решение для перетаскивания объектов по осям X и Z? Это был изнурительный поиск или, возможно, он прошел до того, как меня не заметили. Я новичок в Three.js и реагирую, любая помощь очень ценится.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...