SpriteKit。与重力相反的applyForce混淆

时间:2015-08-06 14:50:54

标签: ios objective-c iphone sprite-kit

我使用下面列出的代码作为SpriteKit的实验。我所做的是对它施加相同数量的力作为重力效应,但是使用反平行向量(体的质量设置为1.0)。通过更新功能在每个帧上执行该功能。我希望物体完全不会移动,因为applyForce和重力相互补偿。

-(void)didMoveToView:(SKView *)view {

  self.anchorPoint = CGPointMake(0.5, 0.5);

  SKShapeNode *node = [SKShapeNode shapeNodeWithRect:CGRectMake(0,0,WIDTH, HEIGHT)];
  node.position = CGPointMake(30, 280);
  node.strokeColor = [SKColor whiteColor];
  node.fillColor = [SKColor purpleColor];
  node.name = @"node";

  CGSize sz = node.frame.size;
  node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:sz center:[GameScene Center]];
  node.physicsBody.restitution = 0.3;
  node.physicsBody.mass = 1.0;
  node.physicsBody.affectedByGravity = YES;

  self.figure = node;

  [self addChild:node];

  self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
}


-(void)update:(CFTimeInterval)currentTime {

  [self.figure.physicsBody applyForce:CGVectorMake(
                                                 - self.physicsWorld.gravity.dx,
                                                 - self.physicsWorld.gravity.dy)];

但是,物体会像重力一样受到影响。我用一个日志来检查质量,它总是正好是1.0

经过一些实验,我发现它有一些神奇的数字。它是150.如果使用下一个更新方法,则对象将被休息:

-(void)update:(CFTimeInterval)currentTime {

[self.figure.physicsBody applyForce:CGVectorMake(
                                                 - self.physicsWorld.gravity.dx,
                                                 -150 * self.physicsWorld.gravity.dy)];

而另一个时刻,如果身体尺寸为150 * 150,则质量自动计算为1.0。无论如何那都无济于事。行为与我们直接设置质量相等的行为相同。

如果有人知道这里发生了什么,请帮忙!

2 个答案:

答案 0 :(得分:2)

Let's say, there is 150 to 1 ratio of points to meters in SpriteKit. If we create a body of size 150*150 then the mass would be exactly one. Ok, that's good, we have a body of mass equals 1.0, we don't change it ourselves. BUT, next we again apply the force opposite to gravity and with the same magnitude. In this case the body will fall again. No good.

Alright, 150 / 1 is point-to-meter, and we need to multiply the force by 150 to balance the forces. We might start thinking "Hmm, there must be some clue in it". May be the gravity vector (0, -9.8) affects not kilos not meters but points! Alright then, let us have body of 150*150 points. To balance the forces we'll need (theoretically):

on one hand the force of gravity: 9.8 Newtons (kilo * meter) / sec ^ 2)

on another hand we applyForce: (1.0 kilo) * 9.8 * (150 points) / (sec^2)

So, here we miss the 150. Anyway,this seems to be little bit stupid, but applyForce is measured in ((points * kilo) / sec ^ 2), but the gravity acceleration is in Newtons ((kilo * meter)/ sec ^ 2) (despite the fact it's described as meters per second in documentation. Meters per second! Acceleration!). Multiply it by mass and get the force.

答案 1 :(得分:1)

你找到了神奇的数字:D

150是"像素到仪表" Sprite-kit中的比例。可以在这里找到一个特别好的解释:look at the second answer by mitchellallison。当您使用update:方法访问重力向量时,请牢记这一比率。