SKPhysicsBody和[SKNode setScale:] [英] SKPhysicsBody and [SKNode setScale:]
问题描述
在我目前使用SpriteKit的项目中,我有一堆精灵需要在不同的时间独立地放大和缩小。问题在于,当我缩放节点时,物理体不会随之缩放,因此它会破坏物理学。这是我为了这个问题而放在一起的一个小例子:
In my current project using SpriteKit, I have a bunch of sprites that need to be scaled up and down independently at various times. The problem is that when I scale the node, the physics body doesn't scale with it so it screws up the physics. Here's a small example I put together for the purpose of this question:
CGSize objectSize = CGSizeMake(100, 100);
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:CGRectMake(0, 0, self.size.width, self.size.height)];
SKSpriteNode *n1 = [SKSpriteNode spriteNodeWithColor:[UIColor blueColor] size:objectSize];
n1.position = CGPointMake(self.size.width/2, 2*self.size.height/3);
n1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n1.physicsBody.affectedByGravity = YES;
[self addChild:n1];
SKSpriteNode *n2 = [SKSpriteNode spriteNodeWithColor:[UIColor redColor] size:objectSize];
n2.position = CGPointMake(self.size.width/2, self.size.height/3);
n2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectSize];
n2.physicsBody.affectedByGravity = YES;
[self addChild:n2];
[n1 setScale:0.5];
注意蓝色精灵(按比例缩小)如何位于红色精灵之上,但你可以告诉它的物理身体仍然有维度我告诉它,它没有扩展。
Notice how the blue sprite (scaled down) sits on top of the red one but you can tell its physics body still has the dimension I told it, and it didn't scale.
很明显,缩小节点不会缩小物理范围。所以我的问题是如果我必须手动完成它,我该怎么做呢?
So obviously, scaling down the node doesn't scale down the physicsBody. So my question is if I have to manually do it, how do I go about it?
我尝试在缩放时用正确的尺寸交换身体,但是然后如果旧的身体有关节等,事情会变得非常复杂......如果我能以某种方式缩放现有的身体,那就简单多了。
I tried swapping the body with one of the right size when scaling, but then things get really convoluted if the old body had joints, etc... It'd be a lot simpler if I could just scale the existing body somehow.
推荐答案
使用 SKAction
或更新循环,您可以创建一个新的 SKPhysicsBody
适当的比例并将其应用于对象。但是,通过这样做,您将失去速度。要解决此问题,您可以执行以下操作:
Using either an SKAction
or the Update loop, you can create a new SKPhysicsBody
with the proper scale and apply it to the object. However, by doing so, you will lose the velocity. To fix this, you can do the following:
SKPhysicsBody *newBody = [SKPhysicsBody bodyWithRectangleOfSize:boxObject.size];
newBody.velocity = boxObject.physicsBody.velocity;
boxObject.physicsBody = newBody;
这篇关于SKPhysicsBody和[SKNode setScale:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!