如何让SKSpriteNode在触摸方向上旋转?

时间:2016-01-11 15:02:23

标签: ios

你能帮我解决一下我的问题吗?

定义CC_RADIANS_TO_DEGREES( ANGLE )(( ANGLE )* 57.29577951f)// PI

- (void)didMoveToView:(SKView )view {     / 在这里设置您的场景* /

 _skyColor = [SKColor colorWithRed:113.0/255.0 green:197.0/255.0 blue:207.0/255.0 alpha:1.0];
[self setBackgroundColor:_skyColor];


//Setup the array to hold the walking frames
NSMutableArray *padlingFrames = [NSMutableArray array];

//Load the TextureAtlas for the bear
SKTextureAtlas *kajakAnimatedAtlas = [SKTextureAtlas atlasNamed:@"KajakImages"];

//Load the animation frames from the TextureAtlas
long numImages = kajakAnimatedAtlas.textureNames.count;
for (int i=1; i <= numImages; i++) {
    NSString *textureName = [NSString stringWithFormat:@"kajak_0%d", i];
    SKTexture *temp = [kajakAnimatedAtlas textureNamed:textureName];
    [padlingFrames addObject:temp];
}
_kajakPadlingFrames = padlingFrames;

//Create kajak sprite, setup position in middle of the screen, and add to Scene
SKTexture *temp = _kajakPadlingFrames[0];
_kajak = [SKSpriteNode spriteNodeWithTexture:temp];

_kajak.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));

[_kajak setScale:0.2];
[self addChild:_kajak];

}

- (void)touchesBegan:(NSSet *)触及withEvent:(UIEvent )event {     / 触摸开始时调用* /

CGPoint touchLocation = [[touches anyObject] locationInNode:self];

[self updateRotate:touchLocation];

}

  • (无效)updateRotate:(CGPoint)touchLocation {

    float deltaX = touchLocation.x - _kajak.position.x; float deltaY = touchLocation.y - _kajak.position.y;

    浮角= atan2f(deltaY,deltaX); SKAction * action = [SKAction rotateByAngle:CC_RADIANS_TO_DEGREES(angle)duration:5.0];

    [_ kajak runAction:action]; }

皮划艇不会朝我触摸的方向旋转。这是我遗漏的一些事情?请帮我。提前坦克

1 个答案:

答案 0 :(得分:1)

SKSpriteNodes的零角度指向上方(与将零角度视为指向右侧的标准触发功能相反)。我必须创建一个特殊的角度计算功能,以便在我的游戏中考虑到这一点(见下文,在Swift中)。

您可能还需要确保用于位置的坐标系对于精灵和触摸位置是相同的。从你的代码(我对Obj-C不太满意)我相信他们都是基于场景的界限,但我不确定。

// angle between two points
// ------------------------
// SpriteKit's zero angle is pointing up 
// atan2 returns an angle pointing right
// we're usung sprite kit's conventions so removing 90° from the result
//
func spriteAngleFrom(start:CGPoint, to finish:CGPoint) -> CGFloat
{
   let deltaX = finish.x - start.x
   let deltaY = finish.y - start.y 
   return atan2(deltaY,deltaX) - CGFloat.pi/2
}

您还需要使用rotateToAngle,而不是rotateByAngle。我建议你也指定shortestUnitArc:true。