我试图拉近我的角色和地面之间的距离,发现有些东西看起来应该可以满足我的要求,但是它是为box2d的另一个版本编写的。

原版的:

float targetHeight = 3;
float springConstant = 100;

//make the ray at least as long as the target distance
b2Vec2 startOfRay = m_hovercarBody->GetPosition();
b2Vec2 endOfRay = m_hovercarBody->GetWorldPoint( b2Vec2(0,-5) );

overcarRayCastClosestCallback callback;
m_world->RayCast(&callback, startOfRay, endOfRay);

if ( callback.m_hit ) {
    float distanceAboveGround = (startOfRay - callback.m_point).Length();

    //dont do anything if too far above ground
    if ( distanceAboveGround < targetHeight ) {
        float distanceAwayFromTargetHeight = targetHeight - distanceAboveGround;
        m_hovercarBody->ApplyForce( b2Vec2(0,springConstant*distanceAwayFromTargetHeight),
        m_hovercarBody->GetWorldCenter() );
    }
}


我试图将其更改为我认为应该的样子,但它甚至没有调用回调。

var targetHeight = 3;
var springConstant = 100;

//make the ray at least as long as the target distance
startOfRay = new b2Vec2(m_hovercarBody.GetPosition());
endOfRay = new b2Vec(m_hovercarBody.GetWorldPoint( b2Vec2(0,-5)));

function callback(raycast){
    if ( raycast.m_hit ) {
        var distanceAboveGround = (startOfRay - raycast.m_point).Length();

        //dont do anything if too far above ground
        if ( distanceAboveGround < targetHeight ) {
            var distanceAwayFromTargetHeight = targetHeight - distanceAboveGround;
            m_hovercarBody.ApplyForce( b2Vec2(0,springConstant*distanceAwayFromTargetHeight),
        m_hovercarBody.GetWorldCenter() );
        }
    }
}
m_world.RayCast(callback, startOfRay, endOfRay);


任何想法如何将其转换为与box2dweb一起使用?

谢谢

最佳答案

可能是原始代码是为坐标系统工作方式不同的平台编写的。

在Canvas元素中,坐标系从左上角开始,这意味着m_hovercarBody.GetWorldPoint( b2Vec2(0,-5))正在检查字符上方而不是下方的点。

我不确定其余的代码,但尝试将其更改为m_hovercarBody.GetWorldPoint( b2Vec2(0,5))并查看会发生什么。

编辑:

我认为实际上问题出在您构造回调的方式上。查找Raycast函数的参考将为reveal more
(您使用的Box2D的Javascript版本是Actionscript的自动端口。鉴于两者的语法非常相似,您可以使用reference for Flash。)

您发布的原始代码似乎是C ++,但是我对其语法并不了解。似乎有某种类可以进行光线投射(overcarRayCastClosestCallback)。您可以寻找它,也可以根据我发布的第一个链接尝试构建自己的回调函数。可能是这样的:

function customRaycastCallback(fixture, normal, fraction) {
// you can, for instance, check if fixture belongs to the ground
// or something else, then handle things accordingly

    if( /* fixture belongs to ground */ ) {
        // you've got the fraction of the original length of the raycast!
        // you can use this to determine the distance
        // between the character and the ground
        return fraction;
    }
    else {
        // continue looking
        return 1;
    }
}

关于javascript - box2dweb射线广播,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9251828/

10-09 09:11