關(guān)鍵代碼
通過設置定位信息進行移動
mesh.position.set(0, 0, 0);
拖動物體:按住ctrl+按住鼠標左鍵 進行拖動
代碼:?
<template>
? <div id="three_div">
? </div>
</template>
? <script>
import * as THREE from "three";
import {OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
export default {
? name: "HOME",
? components: {
? ? // vueQr,
? ? // glHome,
? },
? data() {
? ? return {
? ? };
? },
? mounted() {
? ? //使用控制器控制3D拖動旋轉(zhuǎn)OrbitControls
? ? //控制3D物體移動
? ? //1.創(chuàng)建場景
? ? const scene = new THREE.Scene();
? ? console.log(scene)
? ?
? ? //2.創(chuàng)建相機
? ? const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
? ? //設置相機位置
? ? camera.position.set(0,0,10);
? ? //將相機添加到場景
? ? scene.add(camera);
? ? //添加物體
? ? //創(chuàng)建幾何體
? ? const cubeGeometry = new THREE.BoxGeometry(2,2,2);
? ? const cubeMaterial = new THREE.MeshBasicMaterial({color: 0xffff00});
? ? //根據(jù)幾何體和材質(zhì)創(chuàng)建物體
? ? const mesh ?= new THREE.Mesh(cubeGeometry, cubeMaterial);
? ? //將物體加入到場景
? ? scene.add(mesh);
? ? //添加坐標軸輔助器
? ? const axesHepler = new THREE.AxesHelper(5)
? ? scene.add(axesHepler)
? ? //初始化渲染器
? ? const ?render = new THREE.WebGLRenderer();
? ? //設置渲染器的尺寸
? ? render.setSize(window.innerWidth, window.innerHeight);
? ? //使用渲染器,通過相機將場景渲染進來
? ? //創(chuàng)建軌道控制器,可以拖動,控制的是攝像頭
? ? const controls = new OrbitControls(camera, render.domElement);
? ? //將webgl渲染的canvas內(nèi)容添加到body上
? ? document.getElementById('three_div').appendChild(render.domElement);
? ? //修改3D位置
? ? mesh.position.set(0, 0, 0);
? ?// render.render(scene, camera);
? ? //渲染下一幀的時候就會調(diào)用回調(diào)函數(shù)
? ? let i=1;
? ? let renderFun = ()=>{
? ? ? mesh.position.x += 0.02*i;
? ? ? if(mesh.position.x >= 5){
? ? ? ? i = -1;
? ? ? }
? ? ? if(mesh.position.x <= 0){
? ? ? ? i = 1;
? ? ? }
? ? ? console.log(1)
? ? ? //需要重新繪制canvas畫布
? ? ? render.render(scene, camera);
? ? ? //監(jiān)聽屏幕刷新(60HZ,120HZ),每次刷新觸發(fā)一次requestAnimationFrame回調(diào)函數(shù)
? ? ? //但是requestAnimationFrame的回調(diào)函數(shù)注冊生命只有一次,因此需要循環(huán)注冊,才能達到一直調(diào)用的效果
? ? ? window.requestAnimationFrame(renderFun);
? ? }
? ?// window.requestAnimationFrame(renderFun);
? ? renderFun();
?? },
? ?methods: {
? },
};
</script>
<style scoped lang="scss">
</style>
效果圖:文章來源:http://www.zghlxwxcb.cn/news/detail-496510.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-496510.html
到了這里,關(guān)于ThreeJS-移動(三)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!