我遇到touchesBegan更新CGVector值的问题

时间:2014-04-28 04:17:53

标签: ios objective-c ios7 sprite-kit

我做了一个CGVector,它使得球员的upward impulse(模拟跳跃)。如果我用我现在拥有的游戏(下图)运行游戏,它将开始正常,并且一旦游戏开始,跳跃将完美地发生。我试图在每次录制触摸时跳球,但我在调用正确的方法/使其工作时遇到问题。

这是我的代码:

#import "MyScene.h"

@interface MyScene ()

@property (nonatomic) SKSpriteNode *paddle;


@end

int jump = 0;


@implementation MyScene

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


NSLog(@"Touch Detected!");

// create the vector
//    myVector = CGVectorMake(0, 15);
//    [ball.physicsBody applyImpulse:myVector];




}

- (void)addBall:(CGSize)size {
SKSpriteNode *ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball"];

// create a new sprite node from an image

// create a CGPoint for position
CGPoint myPoint = CGPointMake(size.width/2,0);
ball.position = myPoint;

// add a physics body
ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:ball.frame.size.width/2];

ball.physicsBody.restitution = 0;

// add the sprite node to the scene
[self addChild:ball];




// create the vector
CGVector myVector = CGVectorMake(0, 15);

// apply the vector
[ball.physicsBody applyImpulse:myVector];


}



-(id)initWithSize:(CGSize)size {    
if (self = [super initWithSize:size]) {
    /* Setup your scene here */
    self.backgroundColor = [SKColor whiteColor];

    // add a physics body to the scene
    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

    // change gravity settings of the physics world
    self.physicsWorld.gravity = CGVectorMake(0, -8);

    [self addBall:size];
//        [self addPlayer:size];


}
return self;
}


-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}

@end

你可以看到我已经在touchesBegan中评论了myVector = CGVectorMake(0, 15);[ball.physicsBody applyImpulse:myVector];,因为它无法找到球,我甚至不确定它是否正确所有。谁能帮我用冲动来实现这个跳跃?谢谢!

1 个答案:

答案 0 :(得分:1)

你在正确的轨道上,但是向量的多次冲动(0,15)将导致球变得非常高。在应用任何后续冲动之前,您需要将球的速度重置为零。

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

    NSLog(@"Touch Detected!");

    // create the vector
    ball.physicsBody.velocity = CGVectorMake(0,0);

    myVector = CGVectorMake(0, 15);
    [ball.physicsBody applyImpulse:myVector];

}

此外,您需要将球声明为全局变量,如下所示:

@implementation MyScene
{
    SKSpriteNode *ball;
}

然后在addBall:方法中,而不是

SKSpriteNode *ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball"];

写一下

ball = [SKSpriteNode spriteNodeWithImageNamed:@"ball"];