我正在尝试使精灵根据屏幕上的触摸平滑地跟随和旋转。玩家不必被迫触摸精灵本身以使其移动,因为他一次只能控制一个精灵。因此,无论触摸在屏幕上的何处,玩家都必须跟随移动。这是我到目前为止所拥有的:
在GameScene.m中:
- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
lastTouchLocation = location;
return YES;
}
- (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
//moveBy determine the translate vector
CGPoint moveBy = ccpSub(lastTouchLocation, location);
[player moveBy:moveBy];
lastTouchLocation = location;
}
这是Player.m:
- (float) calculateAngleForNextPoint:(CGPoint) point
{
CGPoint nextPoint = point;
CGPoint pos = self.position;
float offX = nextPoint.x - pos.x;
float offY = nextPoint.y - pos.y;
float angle = atan2f(offY, offX);
angle = CC_RADIANS_TO_DEGREES(angle);
angle = -angle + 90;
return angle;
}
- (void) moveBy:(CGPoint)_pos
{
CGPoint newPos = ccpSub(self.position, _pos);
float angle = [self calculateAngleForNextPoint:newPos];
self.position = newPos;
self.rotation = angle;
}
这段代码运行良好,但旋转一点也不流畅,主要是当玩家在屏幕上缓慢移动手指时,精灵会发疯!我尝试了很多东西,比如设置动作,但是 touchMoved 方法调用太快而无法使用动作。
我应该怎么做才能解决这个问题?非常感谢!