Reputation: 748
I want to make boxes, and when you hit the boxes with the bullet, the box you hit, will disappear.
I can make it work, by making a single box in a function. But when Im making a function with a for-loop to create several boxes, the app will crash. When i make the SpriteKitNode variable inside the function, the boxes will be shown correctly, but won't disappear when you hit them with the bullet. Now, Im making the variable outside the function, and the app will crash when i run the project.
import SpriteKit
struct PhysicsCategory {
static let Enemy : UInt32 = 1
static let Bullet : UInt32 = 2
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var mainAnimation = SKSpriteNode(imageNamed: "Spaceship")
var squareAnimation = SKSpriteNode(imageNamed: "Squares")
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self
makeBanners()
spaceshipPosition()
makeSquares(numberOfSquaresInRow: 5, numberOfRows: 4, squareRadius: 5, rowSpacing: 40, yStart: 120)
}
And the function, where I assume the error is
func makeSquares (numberOfSquaresInRow: Int, numberOfRows: Int, squareRadius: CGFloat, rowSpacing: CGFloat, yStart: CGFloat) {
for rowNumber in 0...(numberOfRows - 1) {
let squareSpacing = (self.frame.size.width - (CGFloat(numberOfSquaresInRow) * squareRadius * 2)) / CGFloat(numberOfSquaresInRow + 1)
var extraSpacing = CGFloat(0)
if rowNumber % 2 == 1 {
extraSpacing = squareSpacing / 2
}
for squareNumber in 0...(numberOfSquaresInRow - 1) {
squareAnimation.size = CGSize(width: 30, height: 30)
let xPosition : CGFloat = extraSpacing + squareSpacing + squareRadius + (squareRadius * 2 * CGFloat(squareNumber)) + (squareSpacing * CGFloat(squareNumber))
let yPosition : CGFloat = yStart + (CGFloat(rowNumber) * squareSpacing)
squareAnimation.position = CGPoint(x: xPosition, y: yPosition)
squareAnimation.physicsBody = SKPhysicsBody(circleOfRadius: squareRadius)
squareAnimation.physicsBody?.categoryBitMask = PhysicsCategory.Enemy
squareAnimation.physicsBody?.contactTestBitMask = PhysicsCategory.Bullet
squareAnimation.physicsBody?.affectedByGravity = false
squareAnimation.physicsBody?.isDynamic = false
self.addChild(squareAnimation)
}
}
}
Of course, this is not all the codes. Let me know if you need more.
Upvotes: 0
Views: 208
Reputation: 35382
Usually , when you meet an error like:
Terminating app due to uncaught exception 'NSInvalidArgumentException'
it followed by : reason.. so you are be able to understand what happened to your project but here I think the problem is that you add too many times the same node with:
self.addChild(squareAnimation)
so the compiler go to crash because you have just added this node the first time in cycle.
To solve you could add a line immediatly after the FOR cycle to say to compiler "hey , i've a new property, this is my initialization and this happen for each cycle" :
let squareAnim = SKSpriteNode(imageNamed: "Squares")
and work with the rest of the lines with squareAnim
Upvotes: 1