創(chuàng)建場景、相機、軌道控制器、創(chuàng)建網(wǎng)格等

<script setup>
// 導(dǎo)入three.js
import * as THREE from 'three'
// 導(dǎo)入控制器
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 創(chuàng)建場景
const scene = new THREE.Scene();
// 創(chuàng)建相機
const camera = new THREE.PerspectiveCamera(
    45, // 視角 設(shè)置越大視野就越大
    window.innerWidth / window.innerHeight, // 相機的寬度比  取視口的
    0.1, // 近平面
    1000 // 遠平面
)

// 創(chuàng)建渲染器
const renerer = new THREE.WebGLRenderer()
renerer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renerer.domElement)
// 添加軌道控制器
const controls = new OrbitControls( camera, renerer.domElement );
// 可設(shè)置帶阻尼的慣性
controls.enableDamping = true;
// 阻尼值 默認0.05
controls.dampingFactor = 0.05
// 圍繞目標旋轉(zhuǎn)的速度將有多快,默認值為2.0,相當于在60fps時每旋轉(zhuǎn)一周需要30秒。
controls.autoRotate = true

// 創(chuàng)建幾何體
const geometry = new THREE.BoxGeometry(1,1,1);
// 創(chuàng)建材質(zhì)
const material = new THREE.MeshBasicMaterial({ color: '#ff6600' })
// 創(chuàng)建網(wǎng)格
const cube = new THREE.Mesh(geometry, material)
// 父子元素相關(guān)
const childMaterial = new THREE.MeshBasicMaterial({ color: '#00ff68' })
const childCube = new THREE.Mesh(geometry, childMaterial)

// 縮放  作用在父元素 如果父元素放大了  子元素也會跟著放大
cube.scale.set(2,2,2)

// 子元素自己的縮放 在父元素放大的基礎(chǔ)上再進去2倍的放大
// childCube.scale.set(2,2,2)

// 旋轉(zhuǎn) 繞著x軸旋轉(zhuǎn) 45度
childCube.rotation.x = Math.PI / 4
// 利用實例方法
// cube.position.x = 2
cube.position.set(3,0,0)
childCube.position.set(-3,0,0)

// 將網(wǎng)絡(luò)添加到場景中
cube.add(childCube) // 把子元素放在父元素上  坐標位置等都相對于父元素了
scene.add(cube)

// 添加坐標輔助器
const axesHelper = new THREE.AxesHelper(5) // 線段的長度
scene.add(axesHelper)

// 設(shè)置相機位置
camera.position.z = 5
camera.position.y = 2
camera.position.x = 2
camera.lookAt(0,0,0)

// 渲染
const animate = () => {
    requestAnimationFrame(animate)
    // cube.rotation.x += 0.01
    // cube.rotation.y += 0.01
    controls.update()
    renerer.render(scene, camera)
}
animate()
// 監(jiān)聽窗口的變化 
window.addEventListener('resize', () => {
    // 重置渲染器寬高比
    renerer.setSize(window.innerWidth, window.innerHeight)
    // 重置相機寬高比
    camera.aspect = window.innerWidth / window.innerHeight
    // 更新相機投影矩陣
    camera.updateProjectionMatrix()

})
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容