问题
I'm new to SpriteKit and am trying to make a Billiards game but it just doesn't seem to be working properly. The balls don't bounce off each other or the pool cue. I'm not sure what I'm doing wrong. Here is some sample code of one of the balls and the pool cue. Any help will be appreciated!
class PoolTableScene: SKScene, SKPhysicsContactDelegate {
struct PhysicsCatagory {
static let None : UInt32 = 0 //0
static let PokeBall : UInt32 = 0b1 //1
static let PoolCue : UInt32 = 0b1000 //5
static let All : UInt32 = UInt32.max
}
let ballPoke = SKSpriteNode(imageNamed:"pokeBall")
let cuePool = SKSpriteNode(imageNamed: "poolCue")
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
let sceneBody = SKPhysicsBody(edgeLoopFrom: self.frame)
sceneBody.friction = 0
self.physicsBody = sceneBody
ballPoke.name = "ballPoke"
ballPoke.size = CGSize(width: 50, height: 50)
ballPoke.anchorPoint = CGPoint(x:0.5, y:0.5)
ballPoke.position = CGPoint(x: self.frame.size.width*0.25, y:self.frame.size.height/2)
ballPoke.zPosition = 100
ballPoke.physicsBody = SKPhysicsBody(circleOfRadius: 25)
ballPoke.physicsBody?.affectedByGravity = true
ballPoke.physicsBody?.restitution = 10
ballPoke.physicsBody?.linearDamping = 0
self.addChild(ballPoke)
cuePool.name = "poolCue"
cuePool.size = CGSize(width: 100, height: 500)
cuePool.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cuePool.position = CGPoint(x: self.frame.size.width*0.20, y: self.frame.size.height/4)
cuePool.zPosition = 100
cuePool.physicsBody = SKPhysicsBody(circleOfRadius: 50)
cuePool.physicsBody?.affectedByGravity = true
cuePool.physicsBody?.restitution = 10
cuePool.physicsBody?.linearDamping = 0
self.addChild(cuePool)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let positionOfTouch = touch.location(in: self)
ballPoke.physicsBody?.categoryBitMask = PhysicsCatagory.PokeBall
ballPoke.physicsBody?.collisionBitMask = PhysicsCatagory.BlueBall | PhysicsCatagory.OrangeBall | PhysicsCatagory.Border | PhysicsCatagory.PoolCue
cuePool.physicsBody?.categoryBitMask = PhysicsCatagory.PoolCue
cuePool.physicsBody?.collisionBitMask = PhysicsCatagory.BlueBall | PhysicsCatagory.OrangeBall | PhysicsCatagory.PokeBall
}
}
来源:https://stackoverflow.com/questions/39581764/how-to-have-billiards-like-physics-in-spritekit