gpt4 book ai didi

ios - 我在 TouchBegan 更新 CGVector 值时遇到问题

转载 作者:行者123 更新时间:2023-11-29 03:00:44 25 4
gpt4 key购买 nike

我制作了一个CGVector,它使球员球产生向上的冲动(模拟跳跃)。如果我用我目前拥有的东西运行游戏(下图),它会很好地开始,并且在游戏开始时跳跃会完美地发生。每次记录触摸时,我都试图让球跳跃,但我在调用正确的方法/使其工作时遇到问题。

这是我的代码:

#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

你可以看到我已经注释掉了 myVector = CGVectorMake(0, 15);[ball.physicsBody applyImpulse:myVector]; in touchesBegan 因为它可以找不到球,我什至不确定它是否正确。谁能帮我用冲动实现这个跳跃?谢谢!

最佳答案

您在正确的轨道上,但是向量 (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"];

关于ios - 我在 TouchBegan 更新 CGVector 值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com