如何对精灵施加恒定力?

时间:2014-04-29 06:02:29

标签: objective-c sprite-kit skphysicsbody

我有一个精灵,我想应用一个恒定的力,而不是每次更新时重新施加力,这给了我奇怪的结果。

我有一个质量为60公斤且受重力影响的精灵。我想不断施加一个等于引力的力。我正在做的方式仍然导致精灵快速下降,因为重力在某种程度上更大。我想知道如何以及何时施加重力,并且我是否可以在物体上设置恒定的力,类似于重力。

目前,我的场景如下:

#import "MyScene.h"

@interface MyScene ()

@property (nonatomic, strong)SKSpriteNode *parachutist;

@end

@implementation MyScene

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        CGSize spriteSize = CGSizeMake(80.0f, 80.0f);
        self.parachutist = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"parachutist.png"] size:spriteSize];
        [self addChild:self.parachutist];
        self.parachutist.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        self.parachutist.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:spriteSize];
        self.parachutist.physicsBody.dynamic = YES;
        self.parachutist.physicsBody.mass = 60.0;    // kg
        self.parachutist.physicsBody.affectedByGravity = YES;
    }

    return self;
}

- (void)update:(NSTimeInterval)currentTime
{
    // this ought to match the force of gravity
    [self.parachutist.physicsBody applyForce:CGVectorMake(0.0f, 60.0f * 9.8f)];
}

@end

2 个答案:

答案 0 :(得分:0)

修正:

#import "MyScene.h"
#define WEIRD_FACTOR 150.0f
#define GRAVITY -9.8f

@interface MyScene ()

@property (nonatomic, strong)SKSpriteNode *parachutist;

@end

@implementation MyScene

- (id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        CGSize spriteSize = CGSizeMake(80.0f, 80.0f);
        self.physicsBody.affectedByGravity = YES;
        self.physicsWorld.gravity = CGVectorMake(0.0f, GRAVITY / WEIRD_FACTOR);
        self.parachutist = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"Parachutist.png"] size:spriteSize];
        [self addChild:self.parachutist];
        self.parachutist.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        self.parachutist.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:spriteSize];
        self.parachutist.physicsBody.dynamic = YES;
        self.parachutist.physicsBody.mass = 60.0;    // kg
        self.parachutist.physicsBody.affectedByGravity = YES;
    }

    return self;
}

- (void)update:(NSTimeInterval)currentTime
{
    [self.parachutist.physicsBody applyForce:CGVectorMake(0.0f,
                                                          self.parachutist.physicsBody.mass * -GRAVITY)];
}

@end

请参阅此问题以获得解释:applyForce(0, 400) - SpriteKit inconsistency

答案 1 :(得分:-1)

Doctordoder:

我自己是sprite kit的新手,但我目前正在开发游戏。我相信你需要让矢量的Y分量为负。

[self.parachutist.physicsBody applyForce:CGVectorMake(0.0f, -9.8)];

应该直接施加-9.8单位的力量。然而,与重力不同,我不认为这是累积的。重力是-9,8米每秒平方。

通过将重力乘以60,您的重力基本上是正常的60倍。

或者,您可以调整physicsWorld Gravity的属性,并将重力应用于物理主体未设置为physicsBody.dynamic = YES

的任何对象
self.physicsWorld.gravity = CGVectorMake(0, -9.8 );

编辑:语法和标点符号。