我正在开发一个使用Cocos2d-X和Marmalade SDK的游戏。我有几个物体在这个游戏中,在屏幕上移动使用一个游走的指导行为,但我有很多问题,以定位这些物体面对运动方向。
在我的GamObject类update方法( sprite实际上是这个对象的子对象)中,我有:
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度的差别。
发布于 2014-07-07 15:41:34
在我看来,你的方程考虑了屏幕上下一个点的绝对位置,这不会给你适当的旋转。
要修正它,使用速度矢量的方向(我假设它有一个X和Y值可用)来计算精灵的旋转。如果使用此方法,则不需要考虑以前的轮调。
https://stackoverflow.com/questions/24614145
复制相似问题