Create SKSpriteNode with an Asset Programmatically

ぃ、小莉子 提交于 2019-12-22 13:53:50

问题


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:

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:


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")


来源:https://stackoverflow.com/questions/41819373/create-skspritenode-with-an-asset-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!