Sizing and scaling SKSpriteNode

10,493

I was able to figure it out. I am using a random width because that is what I require.

// Scaling
let aspectRatio = self.spriteNode.rSize.width/self.spriteNode.rSize.height
let randWidth = CGFloat(rand(60, 90))
self.spriteNode.size = CGSize(width: randWidth, height: randWidth/aspectRatio)
Share:
10,493
Youssef Moawad
Author by

Youssef Moawad

I am the Founder of the software development group Uzusoft. Uzusoft is currently focused on making mobile apps for iOS (primary field) and Android. We currently have multiple apps on the Apple App Store which you can read about here. I have had a great passion for computers since I was 2 and started learning about programming since I was 9.

Updated on June 16, 2022

Comments

  • Youssef Moawad
    Youssef Moawad almost 2 years

    I have multiple game objects in my iOS game, some of which have a greater resolution than others. The graphics to use for the game object is chosen randomly at runtime. I'd like to make sure that they all don't go over a certain size when used, so I devised the following algorithm:

    while self.spriteNode.rSize.width > 100 && self.spriteNode.rSize.height > 100 {
        self.xScale -= 0.01
        self.yScale -= 0.01
    }
    

    where spriteNode is the object whose texture is the graphic and rSize is an extended computed property on SKSpriteNode that returns the size of the accumulated frame of the node.

    Often, this results in an infinite loop. What's the problem?

    UPDATE 1

    Based on LearnCocos2D's comment, I have tried the following:

    let reqXScale = 50/self.spriteNode.rSize.width
    let reqYScale = 50/self.spriteNode.rSize.height
    self.xScale = reqXScale
    self.yScale = reqYScale
    

    Though this solves the infinite loop issue, some objects are squished rather than keeping their original aspect ratio.

    Also, here's the code that defines rSize:

    var rSize: CGSize {
        return self.calculateAccumulatedFrame().size
    }
    

    I have used this reliably multiple times before.