【发布时间】:2018-01-17 21:35:49
【问题描述】:
我正在制作一个游戏,其中一个球(人)必须穿过一个旋转圆圈(圆圈)中的开口并击中目标。我将碰撞检测设置为旋转圆,然后尝试让球(家伙)通过它而不通过开口。我知道这与碰撞检测有关。此外,我将 circleOfRadius 设置为半径,但我似乎无法为球通过。如果您能提供帮助,我很乐意听取您的意见。这是我的代码,它不是全部,它只是重要的。
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var circle = SKSpriteNode()
var guy = SKSpriteNode()
let guyCategory :UInt32 = 0x1 << 0
let circleCategory :UInt32 = 0x1 << 1
override func didMove(to view: SKView) {
self.physicsWorld.contactDelegate = self
scene?.anchorPoint = CGPoint(x: 0, y: 0)
backgroundColor = UIColor.lightGray
circle = SKSpriteNode(imageNamed: "Circle1")
circle.position = CGPoint(x: self.frame.size.width / 2, y:
self.frame.size.height / 2)
circle.physicsBody = SKPhysicsBody(circleOfRadius: 298 )
circle.physicsBody?.isDynamic = false
circle.physicsBody?.allowsRotation = true
circle.physicsBody?.affectedByGravity = false
circle.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat.pi * 2.0, duration: 7.0)), withKey: "rotatecircle")
self.addChild(circle)
guy = SKSpriteNode(imageNamed: "Guy")
guy.position = CGPoint(x: self.frame.size.width/2 , y:40)
guy.name = "guy"
guy.physicsBody = SKPhysicsBody(circleOfRadius: guy.size.width/2)
guy.physicsBody?.isDynamic = false
guy.physicsBody?.affectedByGravity = false
self.addChild(guy)
circle.physicsBody?.categoryBitMask = circleCategory
circle.physicsBody?.collisionBitMask = targetCategory
circle.physicsBody?.contactTestBitMask = targetCategory
guy.physicsBody?.categoryBitMask = guyCategory
guy.physicsBody?.collisionBitMask = targetCategory
guy.physicsBody?.contactTestBitMask = targetCategory
}
func didBegin(_ contact: SKPhysicsContact) {
let collision1:UInt32 = contact.bodyA.categoryBitMask
if collision1 == targetCategory {
backgroundColor = UIColor.green
}
else {
backgroundColor = UIColor.red
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.physicsWorld.gravity = CGVector(dx: 0 ,dy: 10);
guy.physicsBody = SKPhysicsBody(circleOfRadius: guy.size.width / 2)
}
override func update(_ currentTime: TimeInterval) {
}
}
【问题讨论】:
-
你用
SKPhysicsBody(circleOfRadius: 298 )为你的整个圈子创建了一个物理体。这也包括你在圈子里的开口。您可以使用 SKPhysicsbody 类的init(texture:alphaThreshold:size:)来复制物理体中的圆+孔的形状 -
谢谢!!但是我在使用纹理时并不熟悉,现在了解更多。
-
只需将纹理分配给您的 spritenode,而不是像这样的图像:
circle = SKSpriteNode(texture: SKTexture(imageNamed: "Circle1"))然后您可以访问纹理属性并创建这样的物理体:circle.physicsbody = SKPhysicsbody(texture: circle.texture!, size: CGSize(width: circle.frame.width, height: circle.frame.height)) -
哥们,你是最棒的。太感谢了!它奏效了。
-
不客气,很高兴它对你有用。我发布了一个正式的答案,如果你能接受它会很棒。
标签: ios swift collision-detection game-physics