简体   繁体   中英

Swift 4 SpriteKit SKTexture scaling issue

I am working on a simple game application and am stuck on a really weird scaling problem. I have extended SKSpriteNode to make a class that represents an obstacle in my game world. This obstacle has its @1x, @2x, and @3x images all set in Assets.xcassets

My problem is that no matter what the SKTexture I load and pass into the super.init ends up being exactly 50% of the size of my actual image. So it's as if it's using the @n-1x values even though it isn't (confirmed by removing the @1x and @3x images for a test).

Code:

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();
    }
}

I am testing on a @2x device and after reading the SKTexture.size() documentation I see that it returns the size values in points not pixels, so I created this workaround:

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);
    }
}

This workaround solves my problem but I cannot believe that there is no functionality to avoid this. All of my other image assets such as background, buttons, player model, etc. function just fine in terms of size however all of their images are set through the .sks scene editor, not programmatically.

I do not have any code anywhere else that modifies the scale or size of the Obstacle objects in any way.

Also note that I omitted irrelevant code that sets x and y position, physics, etc.

I am new to iOS development and any help with this issue is much appreciated!

You should not be playing with scale, the system picks the correct scale image for you. Your code should look like this:

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)

Note that I did not include an extension of any kind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM