02-three.js Transform objects
The ultimate Three.js course whether you are a beginner or a more advanced developerhttps://threejs-journey.com/?c=p3
three.js属性学习
- 移动对象 .position
- 缩放对象 .scale
- 旋转 .rotation
- 视角看向 .lookAt
- 坐标轴辅助 Axes Helper
import * as THREE from 'three'// Canvas
const canvas = document.querySelector('canvas.webgl')// Scene
const scene = new THREE.Scene()/*** Object*/
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 })
const mesh = new THREE.Mesh(geometry, material)
// scene.add(mesh)/*** Object Group*/
const group = new THREE.Group()
group.scale.y = 2
group.rotation.y = 0.2
scene.add(group)const cube1 = new THREE.Mesh(new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color: 0xff0000})
)
cube1.position.x = - 1.5
group.add(cube1)const cube2 = new THREE.Mesh(new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color: 0xff0000})
)
cube2.position.x = 0
group.add(cube2)const cube3 = new THREE.Mesh(new THREE.BoxGeometry(1,1,1),new THREE.MeshBasicMaterial({color: 0xff0000})
)
cube3.position.x = 1.5
group.add(cube3)/*** 移动对象*/
// position是Vector3类的实例
// mesh.position.x = 0.7
// mesh.position.y = - 0.6
// mesh.position.z = 1// position1 得到向量的长度
// console.log(mesh.position.length())// position2 可以得到与另一个 Vector3 的距离(请确保在创建相机后使用此代码)
// console.log(mesh.position.distanceTo(camera.position))// position3 可以将把向量的长度减少到 1 个单位,但保持它的方向,normalize
// console.log(mesh.position.normalize())// position4 使用 set(...) 方法来更改值
// mesh.position.set(0.7, - 0.6, 1)/*** 缩放对象*/
// mesh.scale.x = 2
// mesh.scale.y = 0.25
// mesh.scale.z = 0.5/*** 旋转*/
// 注意旋转不是vector3,而是Euler,轴的值以弧度表示,注意万向节锁的问题
// y轴旋转,想象旋转木马
// x轴旋转,想象旋转乘坐时的汽车轮子
// z轴旋转,想象在飞机前面的螺旋桨
mesh.rotation.x = Math.PI * 0.25
mesh.rotation.y = Math.PI * 0.25/*** Sizes*/
const sizes = {width: 800,height: 600
}/*** Camera*/
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height)
camera.position.z = 3
scene.add(camera)/*** lookAt 目标必须是vector3*/
// camera.lookAt(new THREE.Vector3(0,-1,0))
camera.lookAt(mesh.position)/*** Axes Helper 坐标轴辅助*/
const axesHelper = new THREE.AxesHelper(2)
scene.add(axesHelper)/*** Renderer*/
const renderer = new THREE.WebGLRenderer({canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)
renderer.render(scene, camera)
项目创建参考
01-three.js vite基础示例_three.js示例-CSDN博客文章浏览阅读377次。three.js 基本示例代码_three.js示例https://blog.csdn.net/gaowxx/article/details/147954918?spm=1001.2014.3001.5501