Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizing and scaling SKSpriteNode

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.

like image 938
Youssef Moawad Avatar asked Nov 23 '14 09:11

Youssef Moawad


1 Answers

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)
like image 75
Youssef Moawad Avatar answered Sep 28 '22 02:09

Youssef Moawad