Swift 4 SpriteKit SKTexture扩展问题

时间:2018-05-25 04:05:45

标签: swift xcode sprite-kit skspritenode sktexture

我正在开发一个简单的游戏应用程序,并且陷入了一个非常奇怪的扩展问题。我已经扩展了SKSpriteNode来创建一个代表我游戏世界的障碍的类。这个障碍的所有@ 1x,@ 2x和@ 3x图像都在Assets.xcassets中设置

我的问题是,无论我加载什么SKTexture并传入super.init最终都是我实际图像大小的50%。所以就好像它使用的是@ n-1x值,即使它不是(通过删除测试的@ 1x和@ 3x图像来确认)。

代码:

import SpriteKit

class Obstacle: SKSpriteNode {

init(imageNamed: String, type: UInt32, xPos: CGFloat = 0, yPos: CGFloat = 800) {
    let texture = SKTexture(imageNamed: imageNamed);
    super.init(texture: texture, color: SKColor.clear, size: texture.size();
    }
}

我在@ 2x设备上进行测试,在阅读了SKTexture.size()文档后,我发现它返回的点的大小值不是像素,所以我创建了这个解决方法:

import SpriteKit

class Obstacle: SKSpriteNode {

let scale = UIScreen.main.scale

init(imageNamed: String, type: UInt32, xPos: CGFloat = 0, yPos: CGFloat = 800) {
    let texture = SKTexture(imageNamed: imageNamed);
    super.init(texture: texture, color: SKColor.clear, size: CGSize(width: texture.size().width * scale, height: texture.size().height * scale);
    }
}

这种解决方法解决了我的问题,但我无法相信没有功能可以避免这种情况。我的所有其他图像资源(如背景,按钮,播放器模型等)在大小方面都运行良好,但所有图像都是通过.sks场景编辑器设置的,而不是以编程方式设置。

我没有任何代码以任何方式修改Obstacle对象的比例或大小。

另请注意,我省略了设置x和y位置,物理等的无关代码。

我是iOS开发的新手,对此问题的任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

您不应该使用比例尺,系统会为您选择正确的比例图像。您的代码应如下所示:

import SpriteKit

class Obstacle: SKSpriteNode {



init(imageNamed: String, type: UInt32, xPos: CGFloat = 0, yPos: CGFloat = 800) {
    let texture = SKTexture(imageNamed: imageNamed);
    super.init(texture: texture, color: SKColor.clear, size: Texture.size());
    }
}

...

let obstacle =  Obstacle(imageNamed:“myImage”,type:0)

请注意,我没有添加任何类型的扩展程序。

相关问题