1

Completely new to SpriteKit. Currently I have a UIView, and I want to add a sprite node to it (like a small UIImageView, but I want animation for it so using SpriteKit). Therefore I didn't initialize my project to be a game project, as found in almost all of tutorials for SpriteKit. I've found a note here: link and what I have now is sth like:

func initializeImage() {
    let imageView = SKView()
    imageView.frame = CGRect(x: self.frame.width / 2 - Constants.imageWidth / 2, y: self.frame.height - Constants.imageHeight, width: Constants.imageWidth, height: Constants.imageHeight)
    // so place it somewhere in the bottom middle of the whole frame
    let sheet = SpriteSheet(texture: ...)
    let sprite = SKSpriteNode(texture: sheet.itemFor(column: 0, row: 0))
    sprite.position = imageView.center //basically the same position as the imageView.frame's x and y value
    let scene = SKScene(size: imageView.frame.size)
    scene.backgroundColor = SKColor.clear
    scene.addChild(sprite)
    imageView.presentScene(scene)
    self.frame.addSubview(imageView)
}

The SpriteSheet is similar to this: sprite sheet; it's essentially cutting an image atlas and divide it into smaller images. I tracked the process and this step is indeed giving the smaller image (the var 'sprite'). But if running I only have a black square now (should be the size as defined by Constants). If I set scene.backgroundColor to be white then it's white. May I know how I should proceed from here, as how should I make the sprite showing up?

Community
  • 1
  • 1
richards
  • 517
  • 9
  • 27

1 Answers1

1

All of your code looks good except for this:

sprite.position = imageView.center // basically the same position as the imageView.frame's x and y value

That is basically not the position you think it is. The coordinate system in SpriteKit is a) relative to the (SK)scene, not to whatever view the SKView is contained in, and b) flipped vertically relative to the UIKit coordinate system. If you want a sprite centered in the scene, you probably want to set its position based on the scene's size:

sprite.position = CGPoint(x: scene.size.width / 2, y: scene.size.height / 2)

By the way, the external SpriteSheet code might not be needed (and you're more likely to benefit from Apple's optimizations) if you slice up your sprite sheet and put it in an Xcode asset catalog.

rickster
  • 124,678
  • 26
  • 272
  • 326
  • could you possibly have a look at a similar question [here](http://stackoverflow.com/questions/42383395/metal-crash-upon-adding-skspritenode-to-skeffectnode) – user3765506 Feb 28 '17 at 20:48