Monday, April 10, 2017

Swift allow user to choose player Sprite Node

Leave a Comment

I'm trying to allow the user to select their preferred player type/design.

In my gameScene I simply have 1 SKSpriteNode with a texture however I'd like the user to have the option to select between 3 different players.

The only way I can think of doing this is to have the 3 player options all linked to their own gameScene.. And when the user selects the preferred player it will transition to the related gameScene?

The 3 gameScenes would be identical, only that the texture for the player SpriteNode would be different.

This doesn't seem very efficient at all. But I'm a novice and just trying to use knowledge I've gathered so far.

Is there a more efficient way of doing this?

1 Answers

Answers 1

Although I'm not entirely sure how to interpret your question, here goes!

I would recommend creating a bit of logic to allow you to insert the avatar in the selection scene, as well as your game scene.

extension SKSpriteNode {     enum AvatarType {         case blueMan         case purpleWizard         case greyDinosaur     }      class func avatar(withType type: AvatarType) -> SKSpriteNode {         let spriteName: String         switch type {         case .blueMan:             spriteName = "blueManSprite"         // case .purpleWizard         //   ...         default:             spriteName = "someSprite"         }          return SKSpriteNode(imageNamed: spriteName)     } } 

In your SKScene subclasses (or anywhere of course ;) ), you can create avatars like so:

class ChooseAvatarScene : SKScene {     let avatarBlueMan = SKSpriteNode.avatar(withType: .blueMan)     // let avatarWizard = ...     // let avatarDinosaur = ...      func setup() {         avatarBlueMan.position = CGPoint(x: 50, y: 50)         // avatarWizard.position = ...         // avatarDinosaur.position = ...          addChild(avatarBlueMan)         addChild(avatarWizard)         addChild(avatarDinosaur)     }      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {         // check if any of the touches hit an avatar sprite     } } 

Of course, the sprite nodes need to be put in the right position. After that, you need to implement touch handling so register when the user touches a node.

The benefit of this approach is that the Avatar nodes are reusable across different scenes - so if you would want to change the sprite for the wizard, there's only one place you have to change it. Note that the SKSpriteNode extension in the example is very simple - if you want anything more than a single sprite I would recommend subclassing SKSpriteNode instead.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment