简体   繁体   English

在box2d Javascript示例中简单的一般rayCasting

[英]Simple general rayCasting in box2d Javascript example

I've been looking through various tutorials on rayCasting with Box2D, but I haven't seen any clear examples. 我一直在用Box2D查看有关rayCasting的各种教程,但我没有看到任何明显的例子。 I was hoping someone familiar with box2dweb would be able to give a clear example of how one would go about setting up a simple function that would end up looking something like this: 我希望熟悉box2dweb的人能够给出一个明确的例子,说明如何设置一个简单的函数,最终看起来像这样:

var myRayCastFunction = function(p1,p2,maxFraction){
    //Code here
}

The idea being that it would be usable like this: 这个想法是它可以像这样使用:

var retVal = myRayCastFunction(p1,p2,maxFraction)
var fixture = retVal.fixture
var point = retVal.point
var normal = retVal.normal
var fraction = retVal.fraction

(in this case, I'm simply returning 1 intersection, say the nearest one, but would want to know how to make a similar one where retVel is a list of these outputs for each intersection) (在这种情况下,我只是返回1个交叉点,说最近的一个,但是想要知道如何制作类似的一个,其中retVel是每个交叉点的这些输出的列表)

I've been trying to understand all of the details of how RayCasting works in box2D, and I understand that this requires making a custom callback function (I think?), but I never figured out where that function needs to be placed, and what IT should be as well. 我一直在努力了解RayCasting如何在box2D中工作的所有细节,我明白这需要制作一个自定义回调函数(我想?),但我从来没有弄清楚该函数需要放在哪里,以及什么IT也应该如此。

I started to answer this question because I happened to be about to add raycasting to my current project, and I realized there were actually some bugs in box2dweb that needed to be fixed before I could get it done. 我开始回答这个问题,因为我碰巧要将光线投射添加到我当前的项目中,并且我意识到box2dweb中确实存在一些需要修复的错误才能完成。 I'll link to the details instead of cluttering up this post: http://www.iforce2d.net/box2dweb-fixes.txt 我将链接到详细信息而不是弄乱这篇文章: http//www.iforce2d.net/box2dweb-fixes.txt

Here is how I've used the raycast callback successfully. 这是我成功使用raycast回调的方法。 Declare your callback class and give it a ReportFixture function: 声明你的回调类并给它一个ReportFixture函数:

var RaycastCallback = function() {
    this.m_hit = false;
}
RaycastCallback.prototype.ReportFixture = function(fixture,point,normal,fraction) {

    if ( ... not interested in this fixture ... ) 
        return -1;

    this.m_hit = true;
    this.m_point = point;
    this.m_normal = normal;
    return fraction;
};

Now make an instance of that to pass to the worlds RayCast function: 现在创建一个实例来传递给世界的RayCast函数:

var rayStart = ...;
var rayEnd = ...;

var callback = new RaycastCallback();

world.RayCast(callback, rayStart, rayEnd);
if ( callback.m_hit ) {
    ... use callback.m_point etc ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM