简体   繁体   中英

Sprite-kit physicsBody applyImpulse

Currently what my app does: When the ball is moving and u tap the ball changes direction and heads the opposite way. (up and down) (NO left to right) (0 = UP , 1 = DOWN, 2 = NOT MOVING) basically just want the ball to switch direction every time u tap.

The problem is: I'm using [ball.physicsBody applyImpulse:CGVectorMake(0, 100)]; this calls some problems because in order to switch directions it has to counter the other force.

I've learned that doubling the force that going to counter the other force works. but lets say i set a variable "ballSpeed"( doesn't exist yet ) ballSpeed * 2 (for the counter force) this would work but wouldn't the number get to high as u get farther though the game ? (possibly maxing the integer number of 2,147,483,647 )

-(void)handleDirectionChange{

if(((location.y>self.frame.size.height/2)&&(ball.position.y<self.frame.size.height/2))||((location.y<self.frame.size.height/2)&&(ball.position.y>self.frame.size.height/2))){

    if(canTap == true){
        NSLog(@"TAPPED-TRUE");

        if(direction == 0 && canTap == true){
            NSLog(@"MOVE-0");
            [ball.physicsBody applyImpulse:CGVectorMake(0, 100)];//hereeee
            canTap = false;
            NSLog(@"CANT TAP");
            direction = 1;

        }
        if(direction == 1 && canTap == true){
            NSLog(@"MOVE-1");
            [ball.physicsBody applyImpulse:CGVectorMake(0, -200)];//hereeeee
            canTap = false;
            NSLog(@"CANT TAP");
            direction = 0;
        }

    }

}


}

Just in case u wanna see the other code

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


     for (UITouch *touch in touches) {
        location = [touch locationInNode:self];
     }

     [self handleDirectionChange];


}


-(void)handleDirection{

[ballParent enumerateChildNodesWithName:@"ball" usingBlock:^(SKNode *node, BOOL *stop) {

    if([ball.name isEqualToString:@"ball"] && (ball.position.y > self.frame.size.height/2-2 && ball.position.y < self.frame.size.height/2+2) ){//when the ball passes middle

        if(canTap == false) {
            canTap = true;
            NSLog(@"CAN TAP");
        }
    }
}];



}







-(void)update:(CFTimeInterval)currentTime {


[self handleDirection];

}

You can use a defined speed and not double it at all , and then before you aplying a new impulse to the physics body you can just make it "stop" by" reseting" it's velocity

physicsBody.velocity=CGVectorMake(0,0);

You already know the direction so you can make a method to set the body to go to the direction after you reset the body's velocity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM