Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js Ray Casting for Collision Detection

I'm trying to draw a line using ray casting. Basically I want to set up some lines coming from my "player" object out in all directions.

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

I want this so I can then use I can see my collision detection visually.

I know I can use different ways to do collision detection, but i'm using this way as a learning detection.

My issue is the code below draws a line but it seems to randomly change length and not always point at the same angle.

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);        

Any help appreciated.

like image 244
james Avatar asked Nov 19 '12 10:11

james


1 Answers

I was trying to do the same thing after seeing that model.. Since I tried to do it the same way and couldn't figure it out, I'll offer an alternative.

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);
    }

}

So now you have a line shooting out of your mesh into whatever the closest intersect is.

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

like image 158
Paul Nispel Avatar answered Oct 12 '22 22:10

Paul Nispel