簡體   English   中英

觸摸和移動精靈跟蹤不好

[英]touch and move sprite doesn't track well

我正在使用 Sprite Kit 構建一個游戲,該游戲需要跟隨用戶的觸摸進行快速精確的移動。 我需要檢測用戶是否觸摸了視圖中的“玩家”,如果他們觸摸了,當他們移動時,玩家精靈需要相應地隨着觸摸而移動。

我現在有這個工作,但是,它不是很精確......移動輸入越多(無需抬起手指),精靈從觸摸位置獲得的偏移量就越大。

這是我現在正在使用的代碼。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{


    if (self.isFingerOnPlayer) {
        UITouch* touch = [touches anyObject];
        CGPoint touchLocation = [touch locationInNode:self];
        CGPoint previousLocation = [touch previousLocationInNode:self];


        // Calculate new position for player
        int playerX = player.position.x + (touchLocation.x - previousLocation.x);
        int playerY = player.position.y + (touchLocation.y - previousLocation.y);

        // Limit x and y so that the player will not leave the screen any
        playerX = MAX(playerX, player.size.width/2);
        playerX = MIN(playerX, self.size.width - player.size.width/2);
        playerY = MAX(playerY, (player.size.width/2)-3+inBoundsOffset);
        playerY = MIN(playerY, (self.size.height - ((player.size.width/2)-3) - inBoundsOffset));


        // Update position of player
        player.position = CGPointMake(playerX, playerY);


    }


}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];

    SKPhysicsBody* body = [self.physicsWorld bodyAtPoint:touchLocation];
    if (body && [body.node.name isEqualToString: @"player"]) {
        NSLog(@"Began touch on player");
        self.isFingerOnPlayer = YES;

    }
}

-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
    self.isFingerOnPlayer = NO;
}

它會檢測觸摸位置,檢查以確保您正在觸摸玩家精靈,如果是,那么當您移動時,精靈也會... (因為玩這個游戲會導致玩家這樣做)。

任何人都可以提出一種更准確的方法來實現這一點,即使在不抬起手指的情況下移動很多時,也能將精靈保持在用戶的手指下?

您必須記住-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event僅在移動手指寫入時才被調用(抱歉無法幫助 Inspector Clouseau 參考)。

實際上發生的情況是,用戶可以非常快速地將他/她的手指從一個位置移動到下一個位置,一旦手指抬起,您的位置更新就會停止。

我建議你做的是創建一個 CGPoint 屬性並讓-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event將位置存儲在 CGPoint 屬性中。

然后在您的-(void)update:(CFTimeInterval)currentTime添加實際將玩家移動到手指坐標的代碼。 這應該會讓事情變得更順暢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM