Swift 4 SpriteKit中SKTexture缩放异常问题求助
Hey there! Let's dig into this weird scaling problem you're having with your Obstacle class. It's super confusing when code-loaded assets behave differently from scene-editor ones, but we can break this down step by step.
First, Rule Out Common Culprits
Double-check your Asset Catalog settings:
Select your obstacle image set in Assets.xcassets, then look at the Attributes Inspector on the right. Make sure the Scale dropdown is set to Scale Factors (not Single Scale). If it's set to Single Scale, iOS will treat the image's pixel dimensions as point dimensions directly—so a 100x100px @2x image would be interpreted as 100x100 points, which renders at 50% size on a @2x device. That exactly matches the issue you're seeing!
Also confirm that the correct scale variants are assigned (you mentioned testing without @1x/@3x, but just make sure @2x is properly linked to the image set).Inspect your Obstacle class initialization:
Double-check your custominitmethod for any accidental scaling changes. For example:class Obstacle: SKSpriteNode { init(texture: SKTexture?) { // Make sure you're using the texture's point size directly super.init(texture: texture, color: .clear, size: texture?.size() ?? .zero) // Avoid any unintended scale overrides here! // self.xScale = 0.5 <-- this would cause exactly the issue you're seeing } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }If you're manually setting the size instead of using
texture.size(), that could also throw things off—SKTexture.size()returns the correct point-based size, so you don't need to adjust it withUIScreen.main.scaleunless you're doing something custom.
Try a Quick Test to Isolate the Issue
To narrow down whether the problem is with texture loading or your custom class, try creating a vanilla SKSpriteNode directly with your image:
let testObstacle = SKSpriteNode(imageNamed: "your-obstacle-image") print(testObstacle.size) // This should match the expected point size
If this test node has the correct size, then the problem is definitely in your Obstacle class's initialization logic. If it's still scaled incorrectly, the issue is with your Asset Catalog setup.
Why Scene-Editor Assets Work Fine
When you add assets via the .sks scene editor, SpriteKit handles texture scaling automatically based on the scene's scale mode and Asset Catalog settings. It uses the same underlying logic as SKSpriteNode(imageNamed:), but since you're not manually initializing the node, you avoid any accidental overrides in custom code.
Cleanup Your Temporary Fix
Once you fix the root cause, you can remove the UIScreen.main.scale adjustment—using the texture's native point size should work perfectly across all device scales.
内容的提问来源于stack exchange,提问作者slugz

