three.js:关于相机position,up,lookAt理解~~~

时间:2021-07-26 04:33:10

       最近对three.js突然感兴趣,搜了一些相关教程准备自学成才,但是发现关于相机的一些属性设置,教程写的还是比较模糊的,理解起来感觉有些困难。不多说先上代码:

        为了便于理解,先手绘了一个三维坐标系,然后更改相应的参数,来进行理解:

let scene = new THREE. Scene();

let camera = new THREE. PerspectiveCamera( 90, window. innerWidth / window. innerHeight, 0.1, 1000);

let renderer = new THREE. WebGLRenderer();

renderer. setSize( window. innerWidth, window. innerHeight);

document. body. appendChild( renderer. domElement);

// x轴
function linexFun(){
var material = new THREE. LineBasicMaterial({
color: 0xFF0000
});

var geometry = new THREE. Geometry();
geometry. vertices. push(
new THREE. Vector3(- 10, 0, 0),
new THREE. Vector3( 10, 0, 0),
);

var line = new THREE. Line( geometry, material);
scene. add( line);
}
linexFun()
// y轴
function lineyFun(){
var material = new THREE. LineBasicMaterial({
color: 0xFFFF00
});

var geometry = new THREE. Geometry();
geometry. vertices. push(
new THREE. Vector3( 0, - 10, 0),
new THREE. Vector3( 0, 10, 0),
);

var line = new THREE. Line( geometry, material);
scene. add( line);
}
lineyFun();
// z轴
function linezFun(){
var material = new THREE. LineBasicMaterial({
color: 0x0000FF
});

var geometry = new THREE. Geometry();
geometry. vertices. push(
new THREE. Vector3( 0, 0, - 10),
new THREE. Vector3( 0, 0, 10),
);

var line = new THREE. Line( geometry, material);
scene. add( line);
}
linezFun();
function render() {
requestAnimationFrame( render);
renderer. render( scene, camera);
}
render();

绘制完成后,页面一片空白,没有任何显示,此时我们的相机处于(0,0,0),所以是只能看见Z轴负轴的一个切面,这个切面是一个点,由于太小所以我们看不见任何东西。于是我给相机设置了一个位置(3,3,3)。

let camera = new THREE. PerspectiveCamera( 90, window. innerWidth / window. innerHeight, 0.1, 1000);
camera. position. x = 3;
camera. position. y = 3;
camera. position. z = 3;

设置之后显示如下图:

three.js:关于相机position,up,lookAt理解~~~

但是这仍然不是我希望显示的,因为X轴与Y,X轴的负半轴都没有显示。因为此时lookAt的方向是默认的Z轴负半轴,而我设置的视角是90度。所以我们此时只能看见Z轴负半轴与Y轴。不能理解的请看下图(灵魂画师  理解一下):

three.js:关于相机position,up,lookAt理解~~~

P点为(3,3,3)相机位置,lookAt方向为过P点平行Z轴,指向Z轴负半轴的一条直线,视角为90度。因此视锥体大致区域为我用红线画出的圆弧区域(不懂的自己按图算一下)。

所以我此时想要让坐标轴完全显示出来,我需要把lookAt指向原点(0,0,0)。PS:指向(0,1,0)之类的位置也可以,并不唯一。

let camera = new THREE. PerspectiveCamera( 90, window. innerWidth / window. innerHeight, 0.1, 1000);
camera. position. x = 3;
camera. position. y = 3;
camera. position. z = 3;
camera. lookAt({
x : 0,
y : 1,
z : 0
});

three.js:关于相机position,up,lookAt理解~~~

至此,整个坐标轴完全显示出来(红色为X轴,黄色Y轴,蓝色Z轴)。此时camera的up方向为默认的(0,1,0)即:

camera. up. x= 0;
camera. up. y= 1;
camera. up. z= 0;

我们尝试将up方向修改为(1,0,0),显示如下图:

three.js:关于相机position,up,lookAt理解~~~

其实up这个属性很简单,很多教程说什么是相机向上的方向,我觉得不贴切反而会让人误解,我更愿意说是坐标轴向上的方向,远点到up点的向量即为整个空间坐标系垂直向上的方向。

总结:

  • camera.postion:相机所在的位置,默认为(0,0,0)
  • camera.lookAt:相机焦点方向,默认为Z轴负半轴方向
  • camera.up:坐标轴向上方向,默认(0,1,0)。PS:要设置在camera.lookAt前才有效