Box2D& Cocos2d-x发现身体的未来位置

时间:2013-03-10 20:36:42

标签: cocos2d-iphone box2d sprite

我正在制作手机游戏,并且无法预测身体/精灵对的未来位置。我用来做这个的方法如下。

1 --futureX作为cocos2d sprite的位置传入,使用CCSprite.getPosition()找到.x

2 - 我正在使用b2Body值来获得加速度和速度,因此我必须将futureX坐标除以PTM_RATIO(在其他地方定义)来更正

3 - 该函数解决了b2Body到达futureX位置所需的时间(基于其x方向加速度和速度),然后利用该时间确定身体的futureY位置应该。我在最后乘以PTM_RATIO,因为坐标用于创建另一个精灵。

4 - 当解决时间时,我有两种情况:一种是x加速!= 0和一种是x加速度== 0.

5 - 我正在使用二次公式和运动方程来求解我的方程式。

不幸的是,我正在创建的精灵并不是我所期望的。它最终位于正确的x位置,但Y位置总是太大。知道为什么会这样吗?请告诉我这里有哪些其他信息有用,或者是否有更简单的方法来解决这个问题!

float Sprite::getFutureY(float futureX)
{
    b2Vec2 vel = this->p_body->GetLinearVelocity();
    b2Vec2 accel = p_world->GetGravity();

    //we need to solve a quadratic equation:
    // --> 0 = 1/2(accel.x)*(time^2) + vel.x(time) - deltaX

    float a = accel.x/2;
    float b = vel.x;
    float c = this->p_body->GetPosition().x - futureX/PTM_RATIO;

    float t1;
    float t2;

    //if Acceleration.x is not 0, solve quadratically
    if(a != 0 ){
        t1 = (-b + sqrt( b * b - 4 * a * c )) / (2 * a);
        t2 = (-b - sqrt( b * b - 4 * a * c )) / (2 * a);
    //otherwise, solve linearly
    }else{
        t2 = -1;
        t1 = (c/b)*(-1);
    }

    //now that we know how long it takes to get to posX, we can tell the y location on the sprites path    
    float time;
    if(t1 >= 0){
        time = t1;
    }else{
        time = t2;
    }
    float posY = this->p_body->GetPosition().y;
    float futureY = (posY + (vel.y)*time + (1/2)*accel.y*(time*time))*PTM_RATIO;

    return futureY;
}

1 个答案:

答案 0 :(得分:1)

解决:

问题出在这一行:

float futureY = (posY + (vel.y)*time + (1/2)*accel.y*(time*time))*PTM_RATIO;

我需要明确地将(1/2)作为一个浮点数。我修好了这个:

float futureY = (posY + (vel.y)*time + (float).5*accel.y*(time*time))*PTM_RATIO;

注意,否则,带加速度的术语被评估为零。