Spritekit 碰撞
Posted
技术标签:
【中文标题】Spritekit 碰撞【英文标题】:Sprite-kit collison 【发布时间】:2016-09-05 00:10:40 【问题描述】:我项目中的所有这些代码都可以正常工作,但我遇到了一些问题。当飞机接触屏幕的边界时,它在接触后开始旋转。我不知道如何制作它,所以它在碰到屏幕边框时不会旋转。只有在我使用时才会出现这个问题:
plane.physicsBody = SKPhysicsBody(texture: plane.texture!, size: plane.size)
其他形式的定义我没问题,但我需要它是纹理的大小。
plane = SKSpriteNode(imageNamed: sett.store() as! String)
plane.size = CGSize(width: 80, height: 80)
plane.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 4)
// scorenode collison off, makes images spin on any contact
plane.physicsBody = SKPhysicsBody(texture: plane.texture!, size: plane.size)
plane.physicsBody?.categoryBitMask = Physics.Plane
plane.physicsBody?.collisionBitMask = Physics.Bird
plane.physicsBody?.contactTestBitMask = Physics.Bird | Physics.Score | Physics.Coin
plane.physicsBody?.affectedByGravity = true
plane.physicsBody?.dynamic = true
plane.zPosition = 2
self.addChild(plane)
// screen boarder so cant leave screen
let boredBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
boredBody.friction = 0
self.physicsBody = boredBody
我的另一个问题是飞机
plane.physicsBody = SKPhysicsBody(texture: plane.texture!, size: plane.size)
但我也需要这个,所以它是纹理的大小。当它在屏幕上击中我的分数节点时,它应该只增加 1 分,但当它穿过 scoreNode 时,它会变化 1 到大约 60 分。我该如何解决这个问题?
let scoreNode = SKSpriteNode()
scoreNode.size = CGSize(width: 800, height: 1)
scoreNode.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 350)
scoreNode.physicsBody = SKPhysicsBody(rectangleOfSize: scoreNode.size)
scoreNode.physicsBody?.affectedByGravity = false
scoreNode.physicsBody?.dynamic = false
scoreNode.physicsBody?.categoryBitMask = Physics.Score
scoreNode.physicsBody?.collisionBitMask = 0
scoreNode.physicsBody?.contactTestBitMask = Physics.Plane
scoreNode.color = SKColor.whiteColor()
// when scoreNode and plane touch && initates score and highScore
if firstBody.categoryBitMask == Physics.Score && secondBody.categoryBitMask == Physics.Plane || firstBody.categoryBitMask == Physics.Plane && secondBody.categoryBitMask == Physics.Score
score += 1
if score >= highScore
highScore = score
scoreLabel.text = "SCORE: \(score)"
highScoreLabel.text = "HIGH SCORE: \(highScore)"
let highScoreDefault = NSUserDefaults.standardUserDefaults()
highScoreDefault.setValue(highScore, forKey: "highScore")
highScoreDefault.synchronize()
else
scoreLabel.text = "SCORE: \(score)"
highScoreLabel.text = "HIGH SCORE: \(highScore)"
【问题讨论】:
【参考方案1】:它在旋转,因为碰撞已经在物理体上赋予了角速度。这是应该的。如果你真的不希望一个物体有角速度,你可以通过设置节点物理体来做到这一点
allowsRotation
属性为 false。
在这种情况下,它会是这样的:
scoreNode.physicsBody?.allowsRotation = false
https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKPhysicsBody_Ref/index.html#//apple_ref/occ/instp/SKPhysicsBody/allowsRotation
【讨论】:
我已经尝试过了,但我收到一条错误消息,提示“'SKSpriteNode' 类型的值没有成员'allowsRotation'” - plane.allowsRotation = false @Joshua Smith @shane:如this answer中所述,该属性已进入物理体,因此plane.physicsBody?.allowsRotation = false
是的,我已经更新了答案(希望)更清楚以上是关于Spritekit 碰撞的主要内容,如果未能解决你的问题,请参考以下文章