我的CCSprite子类有两个名为velX和velY的浮动属性,用于跟踪播放器的速度。当它在游戏层中被刷过时,我找出了滑动的向量方向并开始向那个方向移动。在我的游戏图层的-update:(ccTime)dt
方法中,我调用[player update:(ccTime)dt
(我知道,同名),并且CCSprite类中的该方法具有此代码。
// move
self.position = ccp(self.position.x + self.velX * dt, self.position.y + self.velY * dt);
// do edge checking
// decelerate
#define kDeceleration .95
NSLog(@">velX = %1.1f, velY = %1.1f, fabs(velX) = %1.1f, fabs(velY) = %1.1f", self.velX, self.velY, fabs(velX), fabs(velY));
self.velX *= kDeceleration;
if (fabs(self.velX < 1.0)) self.velX = 0.0;
self.velY *= kDeceleration;
if (fabs(self.velY < 1.0)) self.velY = 0.0;
每次游戏层调用update
时都会调用它,并传入游戏循环使用的相同时间增量。
如果我向正方向滑动,效果很好,但如果任一滑动组件为负(左或向下),则它们直接变为零。如果我拿出条件,一切正常,我只是认为乘以零应该比不断乘以非常小的小数要便宜。
我必须错误地使用fabs()
功能......
编辑:两次滑动的一些样本输出,两个轴都是正数,两个都是一个负数。
>velX = 21.8, velY = 20.6, fabs(velX) = 21.8, fabs(velY) = 20.6
>velX = 20.7, velY = 19.6, fabs(velX) = 20.7, fabs(velY) = 19.6
>velX = 19.7, velY = 18.6, fabs(velX) = 19.7, fabs(velY) = 18.6
>velX = 18.7, velY = 17.7, fabs(velX) = 18.7, fabs(velY) = 17.7
>velX = 17.8, velY = 16.8, fabs(velX) = 17.8, fabs(velY) = 16.8
>velX = -23.0, velY = -19.3, fabs(velX) = 23.0, fabs(velY) = 19.3
>velX = 0.0, velY = 0.0, fabs(velX) = 0.0, fabs(velY) = 0.0
>velX = 0.0, velY = 0.0, fabs(velX) = 0.0, fabs(velY) = 0.0
>velX = 0.0, velY = 0.0, fabs(velX) = 0.0, fabs(velY) = 0.0
>velX = 0.0, velY = 0.0, fabs(velX) = 0.0, fabs(velY) = 0.0
答案 0 :(得分:0)
我认为这个块是语法错误:
self.velX *= kDeceleration;
if (fabs(self.velX < 1.0)) self.velX = 0.0;
self.velY *= kDeceleration;
if (fabs(self.velY < 1.0)) self.velY = 0.0;
应该是这样:
self.velX *= kDeceleration;
if (fabs(self.velX) < 1.0) self.velX = 0.0;
self.velY *= kDeceleration;
if (fabs(self.velY) < 1.0) self.velY = 0.0;
您需要在比较运算符
之前关闭fabs
括号
p / s:没关系,每个人都会一直犯这样的错误:)