iOS SpriteKit 在 space 中实现精灵的随机移动和碰撞之类的东西

iOS SpriteKit make random moving of sprites and something like collision in space

我是SpriteKit新手,略知一二SKPhysicsBody

所以第一个任务是让我的所有屏幕都像 "box",我所有的精灵都将在随机方向移动。所以让我的屏幕精灵的某些侧面必须改变方向并移动到另一个位置。我需要类似 space 碰撞的东西,当精灵永不停止时。

我找到了一些与碰撞有关的代码 here

据我了解,这部分代码解决了我的第一个任务:

    self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    self.physicsBody.categoryBitMask = edgeCategory;
    self.physicsBody.collisionBitMask = 0;
    self.physicsBody.contactTestBitMask = 0;
    self.physicsWorld.gravity = CGVectorMake(0,0);
    self.physicsWorld.contactDelegate = self;

另一个任务方向,我想将这个用于我所有的精灵:

 SKAction *moveAction = [SKAction moveByX:randomX y:randomY duration:.1];   
 SKAction *repeatingAction = [SKAction repeatActionForever:moveAction];

但我认为它会在尝试检测碰撞时卡住,所以我需要再次更改 moveBy 值,但我想我可以初始化移动然后可以将这项艰巨的工作留给碰撞检测,所以问题在这种情况下是如何发起运动的?

您必须使用力和速度而不是 SKActions 来移动精灵。您还必须设置 restitutionlinearDampingfriction 等属性,以防止在碰撞和移动时失去速度。

sprite.physicsBody?.restitution = 1.0
sprite.physicsBody?.friction = 0.0
sprite.physicsBody?.linearDamping = 0.0

您可以对每个sprite施加随机力。

// randomX and randomY are two random numbers.
sprite.physicsBody?.applyForce(CGVectorMake(randomX, randomY))

精灵还需要 categoryBitMaskcollisionBitMask。每个精灵可以相互碰撞或边缘碰撞。

sprite.categoryBitMask = spriteCategory
sprite.collisionBitMask = spriteCategory | edgeCategory 

restitution : This property is used to determine how much energy the physics body loses when it bounces off another object. The property must be a value between 0.0 and 1.0. The default value is 0.2. Availability

friction : The roughness of the surface of the physics body. This property is used to apply a frictional force to physics bodies in contact with this physics body. The property must be a value between 0.0 and 1.0. The default value is 0.2.

linearDamping : A property that reduces the body’s linear velocity. This property is used to simulate fluid or air friction forces on the body. The property must be a value between 0.0 and 1.0. The default value is 0.1. If the value is 0.0, no linear damping is applied to the object.