我正在使用 Cocos2d-X 和 Marmalade SDK 开发游戏。我在这个游戏中有几个对象使用漫游转向行为在屏幕上移动,但是我在将这些对象定向为面向移动方向时遇到很多问题。
在我的 GamObject 类更新方法中( 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 度差异。
最佳答案
在我看来,你的方程式考虑了屏幕上下一个点的绝对位置,这不会给你正确的旋转。
要修复它,请使用速度矢量的方向(我假设它有可用的 X 和 Y 值)来计算 Sprite 旋转。如果您使用此方法,则无需考虑之前的轮换。
关于android - 根据运动定位 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24614145/