用于碰撞检测的Three.js射线投射

时间:2012-11-19 10:23:04

标签: line three.js raycasting

我试图使用光线投射画一条线。基本上我想设置一些来自我的"播放器"四面八方反对。

(如此:https://gamedev.stackexchange.com/questions/35013/how-to-handle-3d-collisions-using-raycasting-with-a-reflection-vector

我想要这样我就可以使用我可以直观地看到我的碰撞检测。

我知道我可以使用不同的方法进行碰撞检测,但我使用这种方式作为学习检测。

我的问题是下面的代码画了一条线,但似乎是随机改变长度而不是总是指向相同的角度。

var ray = new THREE.Ray( player.model.objects.position, new THREE.Vector3(1, 1, 1));

var geometry = new THREE.Geometry();


// my issue is here. I don't think this is the right way use a ray to workout the second vector?

// EDIT: Realized this should be set at player position and outwards. 
//var newx = 300 * ray.direction.x;
//var newz = 300 * ray.direction.z;

// EDIT CODE UPDATE
var newx = (player.model.objects.position.x) + (60 * ray.direction.x);
var newz = (player.model.objects.position.z) + (60 * ray.direction.z);

// THREE.Vector3 {x: 1310.1526178356803, y: 0, z: 1290.8237947033065} 
console.log(player.model.objects.position); 

geometry.vertices.push( player.model.objects.position); 
geometry.vertices.push( new THREE.Vector3(newx, player.model.objects.position.y, newz));

var line = new THREE.Line(geometry, material);

scene.add(line);        

var geometry = new THREE.Geometry(); // my issue is here. I don't think this is the right way use a ray to workout the second vector? // EDIT: Realized this should be set at player position and outwards. //var newx = 300 * ray.direction.x; //var newz = 300 * ray.direction.z; // EDIT CODE UPDATE var newx = (player.model.objects.position.x) + (60 * ray.direction.x); var newz = (player.model.objects.position.z) + (60 * ray.direction.z); // THREE.Vector3 {x: 1310.1526178356803, y: 0, z: 1290.8237947033065} console.log(player.model.objects.position); geometry.vertices.push( player.model.objects.position); geometry.vertices.push( new THREE.Vector3(newx, player.model.objects.position.y, newz)); var line = new THREE.Line(geometry, material); scene.add(line);

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

在看到那个模型之后,我试图做同样的事情。因为我试图以同样的方式做到这一点并且无法弄明白,我会提供另一种选择。

var line;

function update() {

    // Z- DIRECTION
    raycaster.ray.direction.set(0, 0, -1);

    var geometry = new THREE.Geometry();

    intersections = raycaster.intersectObjects( objects );
    if ( intersections.length > 0 ) {
        var geometry = new THREE.Geometry();

        // POSITION OF MESH TO SHOOT RAYS OUT OF
        geometry.vertices.push( obj.position );
        geometry.vertices.push( intersections[0].point );

        scene.remove(line);
        line = new THREE.Line(geometry, new THREE.LineBasicMaterial({color: 0x990000}));
        scene.add(line);
    }

}

所以现在你有一条线从你的网格射线到最近的交叉点。

https://dl.dropbox.com/u/42766757/guy.png