How to have Billiards like physics in SpriteKit?

筅森魡賤 提交于 2019-12-12 04:23:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!