【问题标题】:SKPhysics with Swift and SpriteKitSKPhysics 与 Swift 和 SpriteKit
【发布时间】:2014-10-09 09:59:18
【问题描述】:

我正在尝试使用 Swift 编程语言创建一个 iOS 游戏。 我想在屏幕上使用滑动手势让角色(玩家)上下左右移动

到目前为止一切顺利。但我想要一些物理。我希望播放器与屏幕边缘发生碰撞。 (后来我希望它与其他东西发生碰撞,但我需要先知道代码;)

问题:如何识别 2 个对象(玩家和屏幕边缘)之间的碰撞

   import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var player:SKSpriteNode = SKSpriteNode()
let moveUp = SKAction.moveByX(0, y:2000, duration:10.0) //it is set to 2000 because I want to see if it collides with the edge of the screen
let moveDown = SKAction.moveByX(0, y: -200, duration: 2.0)




// Define the bitmasks identifying various physics objects
let worldCategory:UInt32 = 0x1 << 0
let playerCategory:UInt32 = 0x1 << 1




override func didMoveToView(view: SKView) {

}



override init(size:CGSize) {
    super.init(size: size)
    self.backgroundColor = SKColor.whiteColor()
    player = SKSpriteNode(imageNamed: "Kundvagn1")
    player.position = CGPointMake(self.frame.size.width/2, player.size.height/2 + 20)
    self.addChild(player)


    player.runAction(moveUp)


    self.physicsWorld.gravity = CGVectorMake(0, 0)
    self.physicsWorld.contactDelegate = self




    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size)
    player.physicsBody?.dynamic = true //I dont think the question marks should be there, but Xcode doesn´t accept the code if there is no question marks there
    player.physicsBody?.categoryBitMask = playerCategory
    player.physicsBody?.contactTestBitMask = worldCategory
    player.physicsBody?.collisionBitMask = 0
    player.physicsBody?.usesPreciseCollisionDetection = true




}


func didBeginContact(contact: SKPhysicsContact!) {
    println("Collision")
}

【问题讨论】:

    标签: ios swift sprite-kit skphysicsbody


    【解决方案1】:

    假设您希望左右边缘遮挡,只需将两个SKShapeNode 矩形对象添加到您的场景中,将它们的高度设置为屏幕高度,并将它们放置在屏幕左右边缘之外。设置他们的物理体,你应该很高兴。

    如果您希望屏幕的所有边缘都成为边界,则需要为您的场景设置一个基于线的物理体,详见此处:Add boundaries to an SKScene

    【讨论】:

      【解决方案2】:

      我添加了这个,以防您需要 jonogilmour 的说明中的代码示例。在 viewController 中打开 ShowsPhysics = true 以查看物理。两边都应该是蓝色的。当然,如果您想要联系通知,您可以使用您的位掩码内容添加到此代码中。希望这会有所帮助!

       var leftEdge = SKNode()
          leftEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero, toPoint: CGPointMake(0.0, self.size.height))
          leftEdge.position = CGPointZero;
          self.addChild(leftEdge)
      
          var rightEdge = SKNode()
          rightEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero, toPoint: CGPointMake(0.0, self.size.height))
          rightEdge.position = CGPointMake(self.size.width, 0.0);
          self.addChild(rightEdge)
      

      【讨论】:

      • 我没有使用 rect 但 edgeFromPoint 它似乎适合手头的工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多