Three.js使用Ray检测2个移动物体之间的碰撞

fnc*_*mbo 3 javascript collision-detection three.js

我正在使用THREE.js和WebGL渲染在3D中制作突破性游戏.我想使用THREE.Ray检测弹跳球和底部平台之间的碰撞,这可以由你控制,但我遇到了麻烦.

我已经设法将光线从平台投射到球上(或其他方式)但是一旦我这样做,球就会卡在屏幕中间并且无法动画.

var ray = new THREE.Ray( platform.position, ball.position.subSelf( platform.position ).normalize() );
var intersects = ray.intersectObject( ball );

if ( intersects.length > 0 ) console.log(intersects[0].distance);
Run Code Online (Sandbox Code Playgroud)

我试图消除subSelfnormalize(),但是,打破了检测.

这是游戏和代码可以在script.js中找到:

http://dl.dropbox.com/u/4531743/WebGL/Breakout-3D/index.html

如果您打开控制台,则可以看到如果移动面板,距离值会发生变化,这样做很好.但是球不能被动画,因为在每一帧它被设置到那个位置.

http://dl.dropbox.com/u/4531743/WebGL/Breakout-3D/index.html#disableRay

以上就是我最初的做法,只需计算球和面板的Z位置,看它是否更大并且在面板的宽度(x)坐标内,如果是,则将其反弹.

球的弹跳只是每帧都将固定量的X和Z坐标改变,如果它在任何一个方向上都走得太远,则反转这个数量以使其返回.

fnc*_*mbo 6

经过一些游戏,我把它解决了.

var ray = new THREE.Ray( ball.position, new THREE.Vector3(ball.position.x, ball.position.y, platform.position.z).subSelf( ball.position ).normalize() );

var intersects = ray.intersectObject( platform );

if ( intersects.length > 0 ) {

    var face = intersects[0].face.d,
    dist = intersects[0].distance;

    if(face == 4 && dist <= 7) sizes.ball.velocityZ = -sizes.ball.velocityZ;

};
Run Code Online (Sandbox Code Playgroud)

基本上,就这样我总是从球上直接射出一条射线,如果平台正好位于它下面并且到平台的距离足够近,我会反转球的方向.


Lee*_*ski 5

有一个碰撞检测的例子:http : //stemkoski.github.com/Three.js/Collision-Detection.html

有关如何移动立方体的说明,请参阅:http : //stemkoski.github.com/Three.js/#collision-detection