Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a SKSpriteNode to UIView

I'm stuck on something, maybe someone can help me. I'm working on a iOS swift game (I'm a beginner iOS developer). In the StoryBoard I've added some buttons, some views, etc. I've added a reference (of a rectangle) in my controller like (using ctrl+drag):

@IBOutlet weak var mainBoardGame: UIView!

In my GameScene I'm creating some SKSpriteNodes like:

playerSprite = SKSpriteNode(imageNamed: "playerImg")
playerSprite.position = ....
playerSprite.size = CGSize(width:...,height: ...)
self.addChild(playerSprite)

My problem is that this SKSpriteNodes are displayed behind the rectangle (mainBoardGame) created in my storyboard. I've tried to add something like

playerSprite.zPosition = 100

but still the same.

I'm thinking that it would be better to add my playerSprite directly to my mainBoardGame (because it will be displayed inside of it) but I don't know how to handle a UIView and a SKSpriteNodes. How can we add a SKSpriteNodes to a UIView ? How to handle the z order between them ?

The main question is how to handle a UIView and a SKSpriteNode ? Thanks.

The reason why I've build it in the storyboard is because I put some contraints in order to have a well displayed elements on each of the iPhone screen size.

Is there a way to do that in SpriteKit ?

C.C.

like image 493
CC. Avatar asked Nov 26 '25 04:11

CC.


1 Answers

SpriteKit does not play nicely with subviews. SKScene wants to occupy a view entirely, so the high-performance 2D game engine can work its magic.

Why not just create your game board within your scene, and have the enclosing view occupy constraints? It's harder to provide a more specific answer without more detailed code examples.

like image 115
jglasse Avatar answered Nov 28 '25 16:11

jglasse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!