7

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.

Youssef Moawad
  • 2,846
  • 5
  • 28
  • 50
  • 1
    It would be helpful if you posted the code that defines rSize. – 0x141E Nov 23 '14 at 10:22
  • 1
    wow that is terrible code, you can just derive the required scale factor from the ratio between actual and desired size and assign the result. The while loop will only block the program for a while (or if you have a bug like in this case: forever). Also consider aspect ratio, you may want to update x/y scale separately. – CodeSmile Nov 23 '14 at 10:45
  • why the accumulatedFrame? If the nodes doesn't have any children, it's identical to frame. If it does have children, it will not scale the sprite's content to the new size but to the total size of the sprite AND its children. – CodeSmile Nov 23 '14 at 13:02
  • @LearnCocos2D using self.frame.size makes the node not appear at all. – Youssef Moawad Nov 23 '14 at 15:06

1 Answers1

6

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)
Youssef Moawad
  • 2,846
  • 5
  • 28
  • 50
  • 1
    how to draw an object with exactly 60px width? It is drawn with a huge size – Vyachaslav Gerchicov Sep 01 '17 at 12:46
  • @VyachaslavGerchicov I realize I'm necroanswering a little, but did you figure this out? If not, take a look at `GameViewController` to see what size you're setting `GameScene` to. It could be that the image is the right size, but your scene is not. Debug both `size` values either way, fwiw. – ruffin May 20 '20 at 19:03