Getting Started with iOS for a C# Programmer – Part 6 – Graphics

In this post I set out to create a series of posts that would walk through creating a basic game in Swift. In the post preceding this one I covered collision, and now we are moving on to graphics.

Add Assets

The secret to graphics in Swift seems to be creating assets. If you look to the left hand side of your project, you should see an asset store:

This can be added to:

Create a new image here (in fact, we’ll need two):

Then drag and drop your icons. Mine were kindly provided by my daughter:

Use SKSpriteNode

Once you have an image, it’s a straight-forward process to map it to the game sprite (for which we are currently using a rectangle). As you can see in GameScene.swift, very little actually changes:

    func createAlien(point: CGPoint) -> SKSpriteNode {
        let size = CGSize(width: 40, height: 30)
        
        //let alien = SKShapeNode(rectOf: size)
        let alien = SKSpriteNode(imageNamed: "alienImage")
        alien.size = size
        
        //print(self.frame.minY, self.frame.maxY, self.frame.minX, self.frame.maxX, self.frame.width, self.frame.height)
        alien.position = point
        //alien.strokeColor = SKColor(red: 0.0/255.0, green: 200.0/255.0, blue: 0.0/255.0, alpha: 1.0)
        //alien.lineWidth = 4
        
        alien.physicsBody = SKPhysicsBody(rectangleOf: size)
        
        alien.physicsBody?.affectedByGravity = false
        alien.physicsBody?.isDynamic = true
        
        alien.physicsBody?.categoryBitMask = collisionAlien
        alien.physicsBody?.collisionBitMask = 0
        alien.physicsBody?.contactTestBitMask = collisionPlayer
        
        alien.name = "alien"
        
        return alien

    }
    

It’s worth bearing in mind that this will simply replace the existing rectangles with graphics. As you can probably see from the images above, mine are neither straight, trimmed, nor centered, and so it looks a little skewed in the game. Nevertheless, we’re now in the territory of a playable game:

We’re not there yet, though. The next post is the final one, in which we’ll add a score, deal with the overlapping aliens and probably reduce the size of the ship. Also, if you run this, you’ll see that after a short amount of time, it uses a huge amount of memory tracking all the aliens, so we’ll limit the number of aliens.

References

https://www.raywenderlich.com/49695/sprite-kit-tutorial-making-a-universal-app-part-1

https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_ref-Asset_Catalog_Format/

https://developer.apple.com/documentation/spritekit/skspritenode

Leave a Reply

Your email address will not be published. Required fields are marked *