根据运动定向精灵

时间:2014-07-07 15:22:52

标签: android ios mobile cocos2d-x marmalade

我正在使用Cocos2d-X和Marmalade SDK开发游戏。我在这个游戏中有几个使用漫游转向行为在屏幕上移动的物体,但是我有很多问题要使这些物体朝向移动方向。

在我的GamObject类更新方法中(精灵实际上是这个对象的子级)我有:

void GameObject::update(float dt)
{
    float angle;
    CCPoint newVelocity;

    newVelocity = gameObjectMovement->calculateSteeringForce(dt);

    // Check if the velocity is greater than the limit.
    if (ccpLength(newVelocity) > MAX_WANDER_SPEED)
        newVelocity = ccpMult(ccpNormalize(newVelocity), MAX_WANDER_SPEED);

    nextPosition = ccpAdd(this->getPosition(), ccpMult(newVelocity, dt));

    angle = calculateAngle(nextPosition);

    this->setPosition(nextPosition);
    this->setRotation(angle);

    velocity = newVelocity;
}

计算角度方法是:

float GameObject::calculateAngle(CCPoint nextPosition)
{
    float offsetX, offsetY, targetRotation, currentRotation;
    int divRest;

    currentRotation = this->getRotation();

    // Calculates the angle of the next position.
    targetRotation = atan2f((-1) * nextPosition.y, nextPosition.x);
    targetRotation = CC_RADIANS_TO_DEGREES(targetRotation);

    targetRotation = targetRotation - currentRotation;

    // Make sue that the current rotation is not above 360 degrees.
    if (targetRotation > 0)
    targetRotation = fmodf(targetRotation, 360.0);
    else
        targetRotation = fmodf(targetRotation, -360.0);

    return targetRotation;
}

不幸的是,当我运行此代码时,对象面向各处而不是移动方向。我不知道自己做错了什么。

更新

您好,我已根据您的建议更新了我的代码:

void GameObject::update(float dt)
{
    float angle;
    CCPoint newVelocity;

    newVelocity = gameObjectMovement->calculateSteeringForce(dt);

    // Check if the velocity is greater than the limit.
    if (ccpLength(newVelocity) > MAX_WANDER_SPEED)
        newVelocity = ccpMult(ccpNormalize(newVelocity), MAX_WANDER_SPEED);

    nextPosition = ccpAdd(this->getPosition(), ccpMult(newVelocity, dt));

    angle = calculateAngle(newVelocity);

    this->setPosition(nextPosition);
    this->setRotation(angle);

    velocity = newVelocity;
}

float GameObject::calculateAngle(CCPoint velocity)
{
    float offsetX, offsetY, targetRotation, currentRotation;
    int divRest;

    // Calculate the angle based on the velocity.
    targetRotation = atan2f((-1) * velocity.y, velocity.x);
    targetRotation = CC_RADIANS_TO_DEGREES(targetRotation);

    // Make sure that the rotation stays within 360 degrees.
    if (targetRotation > 0)
        targetRotation = fmodf(targetRotation, 360.0);
    else
        targetRotation = fmodf(targetRotation, -360.0);


    return targetRotation;
}

现在它的工作要好得多,但我仍然看到一些奇怪的行为。实际移动方向/速度与物体正面之间存在90度的差异。

1 个答案:

答案 0 :(得分:1)

在我看来,你的等式考虑了屏幕上下一个点的绝对位置,这不会给你正确的旋转。

要修复它,请使用速度矢量的方向(我假设它有一个X和Y值可用)来计算精灵旋转。如果您使用此方法,则无需考虑先前的轮换。