How would I make an SKShapeNode scale at randomized sizes forever while not exceeding a maximum set size and not smaller than a minimum set size?
1 Answers
One way to do this (if I understand your question correctly), would be have 3 properties of type TimeInterval
that track how long it has been since the sprite was last scaled, how often the sprite should be scaled (which will initialise as 0.5s) and how long the scale action takes (default is the same as the time between scales):
var timeOfLastScale: CFTimeInterval = 0.0
var timePerScale: CFTimeInterval = 0.5
var scaleTime = timePerScale
We initialise the time since the last scale to 0, as it hasn't happened yet. I also use the timePerScale
as the duration of the scale effect, so as soon as it stops scaling, a new scale action starts i.e. the node is constantly scaling. These can be modified in code for different effects.
We also need 2 properties that define the maximum and minimum scale sizes (from 0-100%) and a computed property of the overall scaling range (we make this a computed property so that if you change the max or min scale factors in your code, you don't have to re-calculate scaleRange):
var maxScale; UInt32 = 100
var minScale:UInt32 = 25
var scaleRange: Uint32 {
get {return maxScale - minScale}
}
(I'm assuming that the node can scale between 25% and 100% of it's normal size)
In update:
call a function that checks to see if the scale time interval has passed. If it has, then create and run a new SKAction to scale the node and reset to time since the last scale.
If the scale time hasn't passed yet, do nothing:
override func update(_ currentTime: TimeInterval) {
scaleNode(currentTime)
// Rest of update code
}
func scaleNode(_ currentTime: CFTimeInterval) {
timeSinceLastScale = currentTime - timeOfLastScale
if timeSinceLastScale < timePerScale {return}
// Time per scale has passed, so calculate a new scale actiona and re-scale the node...
let scaleFactor = Float(arc4random_uniform(scaleRange)+minScale)/100
let scaleAction = SKAction.scale(to: scaleFactor,duration: scaleTime)
nodeToBeScaled.run(scaleAction)
timeOfLastScoreDecrement = currentTime
}