Marshall D
Marshall D

Reputation: 454

Referencing/Changing a Node's Size (After you've called it)

Using SpriteKit, Swift 2, Xcode

I'm trying to change one of my Node's size after it has been called even if it isn't unique (Theres a bunch of them).

In less confusing terms I'm trying to change a Node's size without doing it in the initial declaration. This is what I have tried:

self.childNodeWithName("player")?.size.width = 10

However this doesn't work since childNodeWithName returns a Node and not a SKSpriteNode. Since Nodes have no access to "size," this solution doesn't work. I've also tried using

self.childNodeWithName("player")?.setScale(0.5)

Now the problem with this is that I cannot reference this as a number. I'm trying to continuously cut its size in half every time I call this, but I also need to be able to reference its size as a number. To my knowledge setScale doesn't offer this capability.

Any Ideas? Thanks!

Upvotes: 2

Views: 245

Answers (1)

Chris Slowik
Chris Slowik

Reputation: 2879

Sure, you could set a variable to that node. Also cast it to an SKSpriteNode. Then you can do anything an SKSpriteNode can. Here's a simple test case:

let aNode = SKSpriteNode(color: UIColor.blue, size: CGSize(width: 10, height: 10))
aNode.name = "test"
aNode.zPosition = 10
addChild(aNode)

let theNode = childNodeWithName("test") as! SKSpriteNode
theNode.setScale(40)
print(theNode.size) // prints (400, 400)

A solution if you need the physics body to change with it:

let player = childNodeWithName("player") as! SKSpriteNode
let originalArea: CGFloat = player.size.width*player.size.width
let newArea: CGFloat = originalArea / 2.0
let newLength: CGFloat = CGFloat(sqrt(Double(newSize)))

var newScale = newLength/player.size.width
newScale *= player.xScale
player.setScale(newScale)

This is just some math for finding the ratio between the new desired size (In your case, to cut the area in half), and then it adjusts the new scale by this value. When using setScale the physics body changes with it.

Upvotes: 1

Related Questions