Create SKSpriteNode with an Asset Programmatically

2019-05-20 15:06发布

I'm attempting to programmatically create an SKSpriteNode and give it a texture that is in my Assets.xcassets folder. I figured this would be a basic procedure, but I seem to be having a lot of troubles.

For a reference, here is my asset catalog with the ground asset I'm trying to set to a SKSpriteNode:

Asset catalog with ground asset

Here's the code to make the sprite node:

    sprite.texture = SKTexture(image: UIImage(named: spriteName)!)

    sprite.anchorPoint = CGPoint(x: 0, y: 1)

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

    referenceNode.addChild(sprite)

The variable "spriteName" in the first line is having the String "ground" passed into it. However, when I load the game, the ground is missing. Just to make sure the nodes were actually there, I commented out the texture code and just gave them size and a visible color. This worked out so I know the problem is definitely in the asset reference, not in the code logic.

Any point in the right direction would be greatly appreciated. If more information is needed, please do ask as specifically as possible :)

Thanks, Matthew

EDIT:

My original question may have been a bit too complicated. To rephrase in simpler terms:

I have an asset in my asset library called ground. However, when I set the texture of a SKSpriteNode using this code...

sprite.texture = SKTexture(image: UIImage(named: "ground")!)

the texture doesn't show up in app. My question: how do I properly reference the image in my asset library?

1条回答
Luminary・发光体
2楼-- · 2019-05-20 15:47

It seems like you need to explicitly set the size too:

sprite.texture = SKTexture(imageNamed: "myImage1")
sprite.size = sprite.texture!.size()

..or you can specify the image in init:

let sprite = SKSpriteNode(imageNamed: "myImage1")
查看更多
登录 后发表回答