我在做一个小游戏,就像飞鸟一样。我不知道为什么物体不能“看到”我们自己。我在添加一个墙,一个地面和一个幽灵,很奇怪的是,幽灵探测到了一个地面,反之亦然,但墙仍然是看不见的。为什么?
鬼魂应该停在垂直的长方形(墙)上,而不是掉在地上。

struct PhysicsCatagory{
static let Ghost : UInt32 = 0x1 << 1
static let Wall : UInt32 = 0x1 << 2
static let Ground : UInt32 = 0x1 << 3
}
class GameScene: SKScene{
var Ground = SKSpriteNode()
var Ghost = SKSpriteNode()
var Wall = SKSpriteNode()
override func didMove(to view: SKView) {
/*******adding ground***/
Ground = SKSpriteNode(imageNamed: "Ground")
Ground.setScale(0.7)
Ground.position = CGPoint(x: self.frame.midX, y: self.frame.minY)
Ground.physicsBody = SKPhysicsBody(rectangleOf: Ground.size)
Ground.physicsBody?.categoryBitMask = PhysicsCatagory.Ground
Ground.physicsBody?.collisionBitMask = PhysicsCatagory.Ghost
Ground.physicsBody?.contactTestBitMask = PhysicsCatagory.Ghost
Ground.physicsBody?.affectedByGravity = false
Ground.physicsBody?.isDynamic = false
Ground.zPosition = 3
self.addChild(Ground)
/*******adding wall (not working)****/
Wall = SKSpriteNode(imageNamed: "Wall")
Wall.setScale(0.7)
Wall.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 100)
Wall.physicsBody? = SKPhysicsBody(rectangleOf: Wall.size)
Wall.physicsBody?.categoryBitMask = PhysicsCatagory.Wall
Wall.physicsBody?.collisionBitMask = PhysicsCatagory.Ghost
Wall.physicsBody?.contactTestBitMask = PhysicsCatagory.Ghost
Wall.physicsBody?.affectedByGravity = false
Wall.physicsBody?.isDynamic = false
Wall.zPosition = 1
self.addChild(Wall)
/*******adding ghost***/
Ghost = SKSpriteNode(imageNamed: "Ghost")
Ghost.size = CGSize(width: 90, height: 100)
Ghost.position = CGPoint(x: self.frame.midX, y: self.frame.maxY)
Ghost.physicsBody = SKPhysicsBody(circleOfRadius: 50)
Ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost
Ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Wall | PhysicsCatagory.Ground
Ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Wall | PhysicsCatagory.Ground
Ghost.physicsBody?.affectedByGravity = true
Ghost.physicsBody?.isDynamic = true
Ghost.zPosition = 2
self.addChild(Ghost)
}发布于 2017-02-23 13:28:13
看一看这个:
Wall.physicsBody? = SKPhysicsBody(rectangleOf: Wall.size)注意这里的问号。它用于指定可选链
可选链接是用于查询和调用当前可能为零的可选选项的属性、方法和下标的进程。如果可选项包含值,则属性、方法或下标调用将成功;如果可选项为零,则属性、方法或下标调用返回nil。
现在,赋值也是可选链接的一部分。因此,如果属性为零,则分配将失败。
在您的示例中,physicsBody属性为零,因此不计算=操作符右侧的代码。
要做到这一点,请执行以下操作:
Wall.physicsBody = SKPhysicsBody(rectangleOf: Wall.size)一件与此无关的事,但要记住的是:
如果你对两个身体之间的接触检测感兴趣,至少要有一个是动态的。我指出这一点,因为你的墙壁和地面物体是静态的,这意味着无论你如何设置接触掩码,都不会检测到它们之间的接触。
哦,当然,使用camelCase符号来命名类、属性等等。
https://stackoverflow.com/questions/42414633
复制相似问题