Three.js Pointerlockcontrols shooting along y-axis

怎甘沉沦 提交于 2019-12-12 03:14:05

问题


Currently I am developing a FPS with three.js and pointerlockcontrols.

Using the code below I can shoot into any horizontal direction:

var direction = new THREE.Vector3( 0, 0, -1 );
var rotation = new THREE.Euler( 0, 0, 0, "XYZ" );
var cameraDirection = new THREE.Vector3(this.game.usermodel.root.children[0].position.x, this.game.usermodel.root.children[0].rotation._x, this.game.usermodel.root.children[0].position.z);
cameraDirection.copy( direction ).applyEuler( this.game.user.rotation );

var raycaster = new THREE.Raycaster(this.game.usermodel.root.children[0].position, cameraDirection); 

But my code doesn't take the y-axis into account. The line below holds the pitch rotation:

this.game.usermodel.root.children[0].rotation._x

How can I apply this value so I can shoot along the y-axis (vertically into any direction) as well? Currently the bullet is going along a straight line.

Thanks in advance for your assistance.


回答1:


If you are using PointerLockControls and you want to set a raycaster, you can use this pattern:

var direction = new THREE.Vector3();
var raycaster = new THREE.Raycaster(); // create once and reuse
...

controls.getDirection( direction );
raycater.set( controls.getObject().position, direction );

Do not set the camera position or rotation directly if you are using PointerLockControls.

three.js r.71




回答2:


Investigating this a bit more, I finally came up with a workaround myself. It might not be the perfect way to do this, but it works.

It now works like this: I'm getting the basic mesh rotation and apply the euler, I then add the pitch rotation. In this way I pass the horizontal and vertical rotation into the raycaster.

var direction = new THREE.Vector3( 0, 0, -1 );

direction.copy( direction ).applyEuler( this.game.user.rotation );
direction.y = this.game.usermodel.root.children[0].rotation._x;

var raycaster = new THREE.Raycaster(this.game.usermodel.root.children[0].position, direction);

Everyone is still welcome to comment on this or come up with a more elegant solution.



来源:https://stackoverflow.com/questions/29311875/three-js-pointerlockcontrols-shooting-along-y-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!