我遇到的问题是,初始化精灵时,我用相同的方式定义了另一个精灵,并且该精灵显示它具有物理体,因为我看到了绿色轮廓,但是下面的该精灵没有绿色轮廓它,我认为在创建SKPhysicsBody
时出现问题,或者可能是因为我在随机位置创建了13个相同精灵的副本,如第二段代码所示。
@objc func CreateNewAsteroid() {
var asteroid : SKSpriteNode?
let moveAsteroidDown = SKAction.repeatForever(SKAction.moveBy(x: 0, y: -1, duration: 0.01))
let rotateAsteroid = SKAction.repeatForever(SKAction.rotate(byAngle: 25, duration: 5))
let asteroidXpos = randomNum(high: self.frame.size.width/2, low: -1 * self.frame.size.width/2)
let asteroidYpos = randomNum(high: 2.5*self.frame.size.height, low: self.frame.size.height/2)
let asteroidOrigin : CGPoint = CGPoint(x: asteroidXpos, y: asteroidYpos)
asteroid = SKSpriteNode(imageNamed: possibleAsteroidImage[Int(arc4random_uniform(4))])
asteroid?.scale(to: CGSize(width: player.size.height, height: player.size.height))
asteroid?.position = asteroidOrigin
asteroid?.run(moveAsteroidDown)
asteroid?.run(rotateAsteroid)
let asteroidRadius : CGFloat = (asteroid?.size.width)!/2
asteroid?.physicsBody? = SKPhysicsBody(rectangleOf: (asteroid?.size)!)
asteroid?.physicsBody?.categoryBitMask = asteroidCategory
asteroid?.physicsBody?.affectedByGravity = false
asteroid?.physicsBody?.isDynamic = false
asteroid?.physicsBody?.allowsRotation = false
asteroid?.physicsBody?.categoryBitMask = asteroidCategory
asteroid?.physicsBody?.collisionBitMask = 0
asteroid?.physicsBody?.contactTestBitMask = shipCategory
asteroidArray.append(asteroid!)
self.addChild(asteroid!)
}
我创建了13个这样的精灵
for _ in 0...13 {
CreateNewAsteroid()
}
答案 0 :(得分:-1)
与其将SKSpriteNode小行星作为可选对象,还应使其成为非可选对象,以免通过删除?
中的var asteroid : SKSpriteNode?
成为空值
所以您想放var asteroid : SKSpriteNode
进行此更改后,会出现一些错误,告诉您删除一些!
和?
(当然,请务必删除它们)。
然后转到您的GameViewController.swift
文件,并在view.showsPhysics = true
下添加行view.showsNodeCount = true
完成后,您应该在精灵周围看到一个绿色的轮廓。