Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


Home > >

13. June 2014

 

As you can imagine by the name “SpriteKit”, Sprites are a pretty core part of creating a game using SpriteKit.  We are going to continue building on the minimal application we created in the previous part.  I want to point out, this isn’t the recommended way of working with SpriteKit, it is instead the simplest way.  In a proper application we would be more data driven and store our data in SKS files instead of simply adding them to the project.  This is something we will cover later on.  First lets jump right in with code.

 

We are going to replace the the class GameScene we created in the last tutorial.  In SpriteKit, the fundamentals of your game are organized into SKScene objects.  For now we only have one.  Let’s look:

 

import SpriteKit

 

class GameScene: SKScene {

        let sprite = SKSpriteNode(imageNamed: "sprite1.png")

    

    override func didMoveToView(view: SKView) {

        sprite.anchorPoint = CGPoint(x:0.5,y:0.5)

        sprite.xScale = 4

        sprite.yScale = 4

        self.addChild(sprite)

    }

    

    override func mouseDown(theEvent: NSEvent!) {

        self.sprite.position = CGPoint(x:theEvent.locationInWindow.x,y:theEvent.locationInWindow.y)

    }

}

 

We add the sprite “sprite1.png” to our project directory, simply drag and drop it from Finder.  The sprite(s) ill be using are from the zip file available here.  When you run this code, click anywhere and you should see:

 

Sd1

 

Where ever you click the mouse, the sprite will be drawn.

One immediate change you will notice in this code is sprite was moved out of didMoveToView and made a member variable.  This allows us to access sprite in different functions ( although we could retrieve the sprite from the Scene, something we will see later ). In Swift there are only two main ways of declaring a variable, let and var.  var is a variable meaning it’s value can change.  Using let on the other hand you are declaring a the the value cannot change, this is the same as a const in other languages.  As we touched on briefly in the last part, a let declared value can be assigned later using the ? postfix operator.  In this case, it will have the value of nil at initialization, unless one is specifically given like in the code we just did.  One thing you may notice is, unlike C++, C# and Java, Swift currently has no access modifiers.  In other words all variables are publicly available ( there are no private, internal, protected, etc modifiers available ).  Apparently this is only temporary and will be changed in the language later.  This personally seems like a very odd thing not to have in a language from day one.

Since we set the sprite’s anchor to the middle (0.5,0.5), the sprite will be centred to your mouse cursor.  As you can see we added a mouseDown event handler.  This class is available because SKScene inherits UIResponder, this is how you handle I/O events in your scene.  The only other new aspect to this code is:

        sprite.xScale = 4

        sprite.yScale = 4

 

 

This code causes the sprite to be scaled by a factor of 4x.  We do this simply because our source sprite was only 64x64 pixels, making it really really tiny in an empty scene!  As you can see, scaling sprites in SpriteKit is extremely easy.

 

The structure of a SpriteKit game is actually quite simple.  Your SKScene contains a graph of SKNodes, of which SKSpriteNode is one.  There are others too including SKVideoNode, SKLabelNode, SKShapeNode, SKEmitterNode and SKEffectNode.  Even SKScene itself is a SKNode, which is how all the magic happens.  Let’s take a quick look at an SKLabelNode in action.

 

import SpriteKit

 

class GameScene: SKScene {

    

    override func didMoveToView(view: SKView) {

        var label = SKLabelNode();

        label.text = "Hello World"

        label.fontSize = 128

        label.position = CGPoint(x:0,y:0)

        view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)

        self.addChild(label)

    }

    

}

Which predictably enough gives you:

Sd2

 

These nodes however can be parented to make hierarchies of nodes.  Take for example a combination of the two we’ve seen, our sprite node with a text label parented to it.

import SpriteKit

 

class GameScene: SKScene {

    

    override func didMoveToView(view: SKView) {

        view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)

        

        var sprite = SKSpriteNode(imageNamed:"sprite1.png")

        sprite.position = CGPoint(x:100,y:0);

        sprite.xScale = 4.0

        sprite.yScale = 4.0

        

        var label = SKLabelNode();

        label.text = "Jet Sprite"

        label.fontSize = 12

        label.position = CGPoint(x:0,y: 15)

        label.fontColor = NSColor.redColor()

        label.alpha = 0.5

 

        

        sprite.addChild(label)

        

        self.addChild(sprite)

    }

    

}

 

And when you run it:

Sd3

 

There are a few things to notice here.  Each Node get’s its default coordinates from it’s parents.  Since the jet sprite is parented to the scene and the scene’s anchor is set to the middle of the screen, when we position the screen 100 pixels to the right, that’s 100 pixels to the right of the centre of the screen.  Additionally, the text label is positioned relative to the sprite, so it’s positioning is relative to the sprite.  Another thing you might notice is the text is blurry as hell.  That is because the label is inheriting the scaling from it’s parent, the sprite.  As you can see you compose your scene by creating a hierarchy of various types of nodes.  Now if we were to transform the parent sprite, all the transformations will apply to the child nodes.

 

The following example shows how transforming a parent node effects all child nodes.  Spoilers, it also shows you how to Update a Scene… we will cover this in more detail later, so don’t pay too much attention to the man behind the curtain.

import SpriteKit

 

class GameScene: SKScene {

    

    var sprite = SKSpriteNode(imageNamed:"sprite1.png")

    override func didMoveToView(view: SKView) {

        view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)

        

        sprite.position = CGPoint(x:0,y:0);

        sprite.xScale = 8.0

        sprite.yScale = 8.0

        

        var label = SKLabelNode();

        label.text = "Jet Sprite"

        label.fontSize = 12

        label.position = CGPoint(x:0,y: 15)

        label.fontColor = NSColor.redColor()

        label.alpha = 0.5

 

        

        sprite.addChild(label)

        

        self.addChild(sprite)

    }

    

    override func update(currentTime: NSTimeInterval) {

        if(sprite.yScale > 0) {

            sprite.yScale -= 0.1

            sprite.xScale -= 0.1

        }

        else {

            sprite.xScale = 8.0

            sprite.yScale = 8.0

        }

    }

    

}

 

Now if we run this code:

 

 

Each time update() is called, the sprite is reduced in scaling until it disappears, at which point it’s zoomed back to 8x scaling.  As you can see, the child labelNode is scaled as well automatically.

 

Notice how until this point if we wanted to access our sprite across functions we had to make it a member variable?  As I said earlier, there is another option here, you name your nodes and retrieve them later using that name.  Like so:

 

import SpriteKit

 

class GameScene: SKScene {

    

 

    override func didMoveToView(view: SKView) {

        view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)

        var sprite = SKSpriteNode(imageNamed:"sprite1.png")

        

        sprite.name = "MyJetSprite"

        sprite.position = CGPoint(x:0,y:0);

        sprite.xScale = 4.0

        sprite.yScale = 4.0

        

        self.addChild(sprite)

    }

    

    override func update(currentTime: NSTimeInterval) {

        var sprite = self.childNodeWithName("MyJetSprite");

        if(sprite != nil){

            if(sprite.yScale > 0) {

                sprite.yScale -= 0.1

                sprite.xScale -= 0.1

            }

            else {

                sprite.xScale = 8.0

                sprite.yScale = 8.0

            }

        }

    }

    

}

You can perform some pretty advanced searches, such as searching recursively through the tree by prefixing your name with “//“.  You can also search for patterns and receive multiple results.  We will look at this in more details later.

 

This part is starting to get a bit long so I am going to stop now.  The next part will look at more efficient ways of using Sprites, such as using an Atlas, as well as look at basic animation and whatever else I think to cover!

 

Continue to Part 3

,

blog comments powered by Disqus

Month List

Popular Comments

PlayStation Mobile SDK Tutorial 2: Hello World2, Hello Harder!
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


26. April 2012

 

In this tutorial we are going to manually manage the game loop manually.  Additionally we are going to look at the various ways of handling input from the gamepad.  This tutorial builds on the code we developed in the previous tutorial.  As you may recall, we created a “Hello World” sprite and centered it to the camera.  This time, we are going to give the user the ability to control the sprite’s position and size using the gamepad.

 

 

Let’s get straight to the code:

 

using System; using System.Collections.Generic; using Sce.Pss.Core; using Sce.Pss.Core.Environment; using Sce.Pss.Core.Graphics; using Sce.Pss.Core.Input; using Sce.Pss.HighLevel.GameEngine2D; using Sce.Pss.HighLevel.GameEngine2D.Base; using Sce.Pss.Core.Imaging; namespace HelloWorld { public class AppMain { public static void Main (string[] args) { Director.Initialize(); Scene scene = new Scene(); scene.Camera.SetViewFromViewport(); var width = Director.Instance.GL.Context.GetViewport().Width; var height = Director.Instance.GL.Context.GetViewport().Height; Image img = new Image(ImageMode.Rgba,new ImageSize(width,height),new ImageColor(255,0,0,0)); img.DrawText("Hello World", new ImageColor(255,0,0,255), new Font(FontAlias.System,170,FontStyle.Regular), new ImagePosition(0,150)); Texture2D texture = new Texture2D(width,height,false,PixelFormat.Rgba); texture.SetPixels(0,img.ToBuffer()); img.Dispose(); TextureInfo ti = new TextureInfo(); ti.Texture = texture; SpriteUV sprite = new SpriteUV(); sprite.TextureInfo = ti; sprite.Quad.S = ti.TextureSizef; sprite.CenterSprite(); sprite.Position = scene.Camera.CalcBounds().Center; scene.AddChild(sprite); Director.Instance.RunWithScene(scene,true); bool gameOver = false; while(!gameOver) { Sce.Pss.HighLevel.GameEngine2D.Director.Instance.Update(); if(Input2.GamePad.GetData(0).Left.Release) { sprite.Rotate(Sce.Pss.HighLevel.GameEngine2D.Base.Math.Deg2Rad(90)); } if(Input2.GamePad0.Right.Release) { sprite.Rotate(Sce.Pss.HighLevel.GameEngine2D.Base.Math.Deg2Rad(-90)); } if((Sce.Pss.Core.Input.GamePad.GetData(0).Buttons & GamePadButtons.Up) == GamePadButtons.Up) { sprite.Quad.S = new Vector2(sprite.Quad.S.X += 10.0f,sprite.Quad.S.Y += 10.0f); sprite.CenterSprite(); } if((Sce.Pss.Core.Input.GamePad.GetData(0).Buttons & GamePadButtons.Down) == GamePadButtons.Down) { sprite.Quad.S = new Vector2(sprite.Quad.S.X -= 10.0f,sprite.Quad.S.Y -= 10.0f); sprite.CenterSprite(); } if(Input2.GamePad0.Circle.Press == true) gameOver = true; Sce.Pss.HighLevel.GameEngine2D.Director.Instance.Render(); Sce.Pss.HighLevel.GameEngine2D.Director.Instance.GL.Context.SwapBuffers(); Sce.Pss.HighLevel.GameEngine2D.Director.Instance.PostSwap(); } Director.Terminate(); } } }

 

 

 

The top portion of the code is completely unchanged, our new additions start at the line:

Director.Instance.RunWithScene(scene,true);

 

The key addition here is the second parameter “true”.  This bool is telling the Director singleton that we are going to handle the game loop ourselves, this means we need to call 4 methods manually ( described in a moment ).  Next up we create a bool gameOver, which is going to control when we exit our game loop.  Obviously we don’t want to exit right away, so we default it to false.  Speaking of game loops, that’s what the while line does, loops over and over until gameOver is set to true.

 

Now in each iteration of our loop, there are four methods we have to call, Update(), Render(), GL.Context.SwapBuffer() and PostSwap().  Update() tells the director we have moved on to the next frame, Render() draws the frame, SwapBuffers displays what Render() drew on the backbuffer to the screen (makes it visible) and finally PostSwap() tells the director we’ve finished swapping buffers and it must be called after SwapBuffers().  Those four combined represent a complete game loop, all the rest of the code handles input from the game pad.

 

Just to make something perfectly clear here, I am using 3 different ways to check for input, *you won’t do this in your code*.  I am just doing it to illustrate all of your different options in one example.  You should just pick one ( probably Input2 ) and use only it.  Lets look at them one at a time.

 

if(Input2.GamePad.GetData(0).Left.Release) { sprite.Rotate(Sce.Pss.HighLevel.GameEngine2D.Base.Math.Deg2Rad(90)); }

 

 

This method is the most likely way you will deal with Input.  Input2 is a wrapper around the Input object to make things a bit simpler.  GetData takes a parameter telling it which control ( controller 1, controller 2, etc ) you want to poll, returning a GamePadData object, representing the state the controller is in.  We are then checking if the “Left” button has been released.  In the case Left is released, we then rotate our sprite 90 degrees.  Rotate takes an angle value in radians, so we use the Math.Deg2Rad() helper function to convert from degrees to radians.  Of course you could have passed the radian value in instead of converting, 1.5709633 is 90 degrees in radians, it’s just a bit harder to look at.

 

if(Input2.GamePad0.Right.Release) { sprite.Rotate(Sce.Pss.HighLevel.GameEngine2D.Base.Math.Deg2Rad(-90)); }

 

 

This if statement is almost identical to the last one, but instead of using GetData(0), we use a handy alias (GamePad0) that represents exactly the same thing.  The only other difference is, in this case we are checking to see if the “Right” button has been released, and we are rotating by a negative value ( the other way ) if it is.

 

 

if((Sce.Pss.Core.Input.GamePad.GetData(0).Buttons & GamePadButtons.Up) == GamePadButtons.Up) { sprite.Quad.S = new Vector2(sprite.Quad.S.X += 10.0f,sprite.Quad.S.Y += 10.0f); sprite.CenterSprite(); } if((Sce.Pss.Core.Input.GamePad.GetData(0).Buttons & GamePadButtons.Down) == GamePadButtons.Down) { sprite.Quad.S = new Vector2(sprite.Quad.S.X -= 10.0f,sprite.Quad.S.Y -= 10.0f); sprite.CenterSprite(); }

 

 

This time we are using Input directly, using Input instead of Input2.  As you can see, the results are a bit more “raw”.  In this case we have to use bit masking to determine if a given button is pressed and there is no Released option.  In this case we are checking for the “Up” and “Down” buttons.  In the event that the user is pressing Up or Down, we are modifying the Scale of the quad our hello texture is pasted on.  Remember initially Quad.S is equal to the size of the screen in pixels.  If we press Up, we scale the image up 10 pixels in size, if we press down, we shrink it by 10 pixels in size.

 

 

Finally, we check ( using the Input2 method ), if the user has pressed the Circle button, in which case we set gameOver to true, causing our loop to exit and our program to end.

 

 

One thing to notice at this point is how we scaled the sprite.  Unlike rotate, we didn’t call a method, instead we modified the Quad.S(cale) property.  The actual transformation matrix of a node ( which SpriteUV is derived from ) is actually determined combining the Position, Scale, Skew and Rotation+Angle+RotationNormalize properties.  Therefore modifying any of these properties will translate the node accordingly.

 

 

Now run our game, if we press left or right, we rotate 90 degrees, while pressing up or down scales the images.  Finally press Circle to exit.

 

 

helloworld2

 

 

One last thing I suppose needs covering… how exactly do you press Left, Right, or Circle on the simulator?

Left directional key
Cursor key: ←

Up directional key
Cursor key: ↑

Right directional key
Cursor key: →

Down directional key
Cursor key: ↓

Square button
Alphabet: A

Triangle button
Alphabet: W

Circle button
Alphabet: D

Cross button
Alphabet: S

SELECT button
Alphabet: Z

START button
Alphabet: X

L button
Alphabet: Q

R button
Alphabet: E

 

 

Sadly, you cannot currently emulate the analog sticks using the simulator.  Obviously you can on the Vita device.

 

EDIT: Oops, forgot to include the project source code, which you can download here.

Programming , , ,

blog comments powered by Disqus

Month List

Popular Comments