Search code examples
iosobjective-csprite-kittouch

How can I measure sprite's jump strength?


Hello, I am new to spriteKit and I am trying to make a game. In the game I have a player that jumps from stair to stair, which comes from the top of the screen infinitely (Like in Doodle Jump, only the jump is controlled by the player's touch). I am trying to make a jump, by applying an impulse on the player, but I want to control the jump strength by the player's touch duration. How can I do so? The jump executes when the player STARTS touching the screen so I can't measure the jump intensity (By calculating the touch duration) ... Any ideas? Thanks in advance!!! (:


Solution

  • Here's a simple demo to apply the impulse on a node with the duration of touch. The method is straightforward: set a BOOL variable YES when the touch began, and NO when the touch ended. When touching, it will apply a constant impulse in update method.

    To make the game more natural, you might want to refine the impulse action, or scroll the background down as the node is ascending.

    GameScene.m:

    #import "GameScene.h"
    
    @interface GameScene ()
    
    @property (nonatomic) SKSpriteNode *node;
    @property BOOL touchingScreen;
    @property CGFloat jumpHeightMax;
    
    @end
    
    @implementation GameScene
    
    - (void)didMoveToView:(SKView *)view
    {
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    
        // Generate a square node
        self.node = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50.0, 50.0)];
        self.node.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        self.node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.node.size];
        self.node.physicsBody.allowsRotation = NO;
        [self addChild:self.node];
    }
    
    const CGFloat kJumpHeight = 150.0;
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        self.touchingScreen = YES;
        self.jumpHeightMax = self.node.position.y + kJumpHeight;
    }
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        self.touchingScreen = NO;
        self.jumpHeightMax = 0;
    }
    
    - (void)update:(CFTimeInterval)currentTime
    {
        if (self.touchingScreen && self.node.position.y <= self.jumpHeightMax) {
            self.node.physicsBody.velocity = CGVectorMake(0, 0);
            [self.node.physicsBody applyImpulse:CGVectorMake(0, 50)];
        } else {
            self.jumpHeightMax = 0;
        }
    }
    
    @end