以编程方式使用资产创建SKSpriteNode [英] Create SKSpriteNode with an Asset Programmatically

查看:113
本文介绍了以编程方式使用资产创建SKSpriteNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式创建SKSpriteNode并为其提供Assets.xcassets文件夹中的纹理.我认为这将是一个基本过程,但是我似乎遇到了很多麻烦.

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.

作为参考,这是我的资产目录,其中包含我要设置为SKSpriteNode的地面资产:

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)

第一行中的变量"spriteName"正在将字符串"ground"传递给它.但是,当我加载游戏时,地面消失了.为了确保节点确实存在,我注释掉了纹理代码,并给了它们大小和可见的颜色.这样就解决了,所以我知道问题肯定出在资产引用中,而不是在代码逻辑中.

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

谢谢, 马修

我最初的问题可能有点太复杂了.用更简单的措辞重新表达:

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

我的资产库中有一项资产叫地.但是,当我使用此代码设置SKSpriteNode的纹理时...

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?

推荐答案

似乎您也需要显式设置大小:

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

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

..或者您可以在init中指定图片:

..or you can specify the image in init:

let sprite = SKSpriteNode(imageNamed: "myImage1")

这篇关于以编程方式使用资产创建SKSpriteNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆