Raycast是如何工作的,它是避免碰撞的最佳方法吗?

时间:2016-06-02 06:21:30

标签: javascript three.js

我编写了以下代码来尝试一些基本的碰撞。任何人都可以向我解释Raycast如何工作,以及它是否是避免碰撞的最佳/简单方法。我不是在谈论复杂的现实碰撞,只是2D类型。就像避免相机进入墙壁一样。

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 1, 10000);
camera.position.y = 100;
camera.position.z = 500;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

var cuboMat = new THREE.MeshBasicMaterial({color: 0xFF0000});
var cuboGeo = new THREE.CubeGeometry(50,50,50);
var cubo = new THREE.Mesh(cuboGeo, cuboMat);
scene.add(cubo);

var cubo2Mat = new THREE.MeshBasicMaterial({color: 0xFFFF00});
var cubo2 = new THREE.Mesh(cuboGeo, cubo2Mat);
cubo2.position.set(-100,0,0);
scene.add(cubo2);

document.addEventListener("keydown", function(event){

if(event.keyCode == 37){
if(cubo.position.x-50 != cubo2.position.x || cubo.position.z != cubo2.position.z){
    cubo.position.x -= 50;
}
}
if(event.keyCode == 38){
if(cubo.position.z-50 != cubo2.position.z || cubo.position.x != cubo2.position.x){
    cubo.position.z -= 50;
}
}
if(event.keyCode == 39){
if(cubo.position.x+50 != cubo2.position.x || cubo.position.z != cubo2.position.z){
    cubo.position.x += 50;
}
}
if(event.keyCode == 40){
if(cubo.position.z+50 != cubo2.position.z || cubo.position.x != cubo2.position.x){
    cubo.position.z += 50;
}
}

});

function animate(){
requestAnimationFrame( animate );
renderer.render(scene, camera);
}
animate();

0 个答案:

没有答案