我是 SpriteKit 的新手,我对 SKPhysicsBody
略知一二。
所以第一个任务是让我的所有屏幕都像一个“盒子”,我所有的 Sprite 都会在其中随机移动。所以让我的屏幕 Sprite 的某些侧面必须改变方向并移动到另一个位置。当 Sprite 永不停止时,我需要类似空间碰撞的东西。
我找到了一些代码 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;
另一个任务方向,我想将这个用于我所有的 Sprite :
SKAction *moveAction = [SKAction moveByX:randomX y:randomY duration:.1];
SKAction *repeatingAction = [SKAction repeatActionForever:moveAction];
但我认为它会在尝试检测碰撞时卡住,所以我需要再次更改 moveBy 值,但我想我可以初始化运动然后可以将这项艰巨的工作留给碰撞检测,所以问题是如何在这种情况下启动运动?
最佳答案
您必须使用力和速度而不是 SKActions
来移动 Sprite 。您还必须设置 restitution
、linearDamping
和 friction
等属性,以防止在碰撞和移动时失去速度。
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))
Sprite 还需要一个categoryBitMask
和collisionBitMask
。每个 Sprite 都可以相互碰撞或与边缘碰撞。
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.
关于iOS SpriteKit 使 Sprite 随机移动和空间碰撞之类的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28831312/