2014-11-01 2 views
0

SpriteKit의 우주선 데모로 작업 중이며 화면에서 클릭 한 위치로 회전하고 싶습니다.SpriteKit에서 커서 위치를 회전하고 가리키는 방법은 무엇입니까?

나는 그것이 위치 50,50에서 화면 시작을 위로 이동시킵니다 만 한 현재의 코드 :

sprite.position = CGPointMake(50,50); 
SKAction *fly = [SKAction moveByX:0.0F y:50.0F duration:1]; 
[sprite runAction:[SKAction repeatActionForever:fly]; 

가 어떻게 작동 할 것인가?

답변

1

그래서 긴 대답이 당신을 도움이 될 것입니다. (나는 raywenderlich의 책 혜택)

//Math Utilities 
static inline CGPoint CGPointSubtract(const CGPoint a, 
             const CGPoint b) 
{ 
    return CGPointMake(a.x - b.x, a.y - b.y); 
} 

static inline CGPoint CGPointMultiplyScalar(const CGPoint a, 
              const CGFloat b) 
{ 
    return CGPointMake(a.x * b, a.y * b); 
} 

static inline CGFloat CGPointLength(const CGPoint a) 
{ 
    return sqrtf(a.x * a.x + a.y * a.y); 
} 

static inline CGPoint CGPointNormalize(const CGPoint a) 
{ 
    CGFloat length = CGPointLength(a); 
    return CGPointMake(a.x/length, a.y/length); 
} 

static inline CGPoint CGPointAdd(const CGPoint a, 
           const CGPoint b) 
{ 
    return CGPointMake(a.x + b.x, a.y + b.y); 
} 

static const float SHIP_SPEED = 60.0; 

@implementation yourScene 
{ 
    SKSpriteNode *ship; 
    NSTimeInterval _lastUpdateTime; 
    NSTimeInterval _dt; 
    CGPoint _velocity; 
    CGPoint _lastTouchLocation; 
} 

-(void)didMoveToView:(SKView *)view 
{ 
    ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"]; 
    ship.position = CGPointMake(50, 50); 
    [self addChild:ship]; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint touchLocation = [touch locationInNode:self.scene]; 
    [self moveShipToward:touchLocation];//Move Toward 
} 

-(void)update:(CFTimeInterval)currentTime { 
    /* Called before each frame is rendered */ 
    { 
     if (_lastUpdateTime) { 
      _dt = currentTime - _lastUpdateTime; 
     } else { 
      _dt = 0; 
     } 
     _lastUpdateTime = currentTime; 

     CGPoint offset = CGPointSubtract(_lastTouchLocation, ship.position); 
     float distance = CGPointLength(offset); 
     if (distance < SHIP_SPEED * _dt) { 
      ship.position = _lastTouchLocation; 
      _velocity = CGPointZero; 
     } else { 
      [self moveSprite:ship velocity:_velocity]; 
      [self rotateSprite:ship toFace:_velocity]; 
     } 
    } 
} 

- (void)moveShipToward:(CGPoint)location 
{ 
    _lastTouchLocation = location; 
    CGPoint offset = CGPointSubtract(location, ship.position); 
    CGPoint direction = CGPointNormalize(offset); 
    _velocity = CGPointMultiplyScalar(direction, SHIP_SPEED); 
} 

- (void)moveSprite:(SKSpriteNode *)sprite 
      velocity:(CGPoint)velocity 
{ 
    CGPoint amountToMove = CGPointMultiplyScalar(velocity, _dt); 
    sprite.position = CGPointAdd(sprite.position, amountToMove); 
} 

- (void)rotateSprite:(SKSpriteNode *)sprite 
       toFace:(CGPoint)direction 
{ 
    sprite.zRotation = atan2f(direction.y, direction.x); 
} 
관련 문제