How do you make a Node move forever in one direction? - ios

I'm trying to make a vertical endless runner like Doodle Jump in SpriteKit (Xcode 7 beta), but can't figure out how to constantly move a Node upwards.
override func didMoveToView(view: SKView) {
makeBackground()
// Bubble
let bubbleTexture = SKTexture(imageNamed: "bubble.png")
bubble = SKSpriteNode(texture: bubbleTexture)
bubble.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bubble.physicsBody = SKPhysicsBody(circleOfRadius: bubbleTexture.size().height/2)
bubble.physicsBody!.dynamic = false
bubble.physicsBody!.allowsRotation = false
let float = SKAction.moveToY(+yScale, duration: 0.2)
bubble.SKAction.repeatActionForever(runAction(float))
self.addChild(bubble)
}

Just so happen to see your post here after having answered your latest one; and I thought I would answer it as well.
What you just need is the following, which tells SKAction to repeat an action as parameter:
let float = SKAction.repeatActionForever(SKAction.moveToY(+yScale, duration: 0.2))
bubble.runAction(float)
As a side note:
In Swift, it's ok to name your vars like, for instance, float. But it is widely frowned upon because there is a first-class variable, namely, float. But in Swift, float is with an upper case; hence, no conflict here. However, to save our foreheads from being snapped by senior programmers every once and a while, we could name your action as, for instance, "floating", which I find it fitting due to the "-ing" (continuous verb form or gerund) that conveys a sense of action.

Related

Need serious help on creating a comet with animations in SpriteKit

I'm currently working on a SpriteKit project and need to create a comet with a fading tail that animates across the screen. I am having serious issues with SpriteKit in this regards.
Attempt 1. It:
Draws a CGPath and creates an SKShapeNode from the path
Creates a square SKShapeNode with gradient
Creates an SKCropNode and assigns its maskNode as line, and adds square as a child
Animates the square across the screen, while being clipped by the line/SKCropNode
func makeCometInPosition(from: CGPoint, to: CGPoint, color: UIColor, timeInterval: NSTimeInterval) {
... (...s are (definitely) irrelevant lines of code)
let path = CGPathCreateMutable()
...
let line = SKShapeNode(path:path)
line.lineWidth = 1.0
line.glowWidth = 1.0
var squareFrame = line.frame
...
let square = SKShapeNode(rect: squareFrame)
//Custom SKTexture Extension. I've tried adding a normal image and the leak happens either way. The extension is not the problem
square.fillTexture = SKTexture(color1: UIColor.clearColor(), color2: color, from: from, to: to, frame: line.frame)
square.fillColor = color
square.strokeColor = UIColor.clearColor()
square.zPosition = 1.0
let maskNode = SKCropNode()
maskNode.zPosition = 1.0
maskNode.maskNode = line
maskNode.addChild(square)
//self is an SKScene, background is an SKSpriteNode
self.background?.addChild(maskNode)
let lineSequence = SKAction.sequence([SKAction.waitForDuration(timeInterval), SKAction.removeFromParent()])
let squareSequence = SKAction.sequence([SKAction.waitForDuration(1), SKAction.moveBy(CoreGraphics.CGVectorMake(deltaX * 2, deltaY * 2), duration: timeInterval), SKAction.removeFromParent()])
square.runAction(SKAction.repeatActionForever(squareSequence))
maskNode.runAction(lineSequence)
line.runAction(lineSequence)
}
This works, as shown below.
The problem is that after 20-40 other nodes come on the screen, weird things happen. Some of the nodes on the screen disappear, some stay. Also, the fps and node count (toggled in the SKView and never changed)
self.showsFPS = true
self.showsNodeCount = true
disappear from the screen. This makes me assume it's a bug with SpriteKit. SKShapeNode has been known to cause issues.
Attempt 2. I tried changing square from an SKShapeNode to an SKSpriteNode (Adding and removing lines related to the two as necessary)
let tex = SKTexture(color1: UIColor.clearColor(), color2: color, from: from, to: to, frame: line.frame)
let square = SKSpriteNode(texture: tex)
the rest of the code is basically identical. This produces a similar effect with no bugs performance/memory wise. However, something odd happens with SKCropNode and it looks like this
It has no antialiasing, and the line is thicker. I have tried changing anti-aliasing, glow width, and line width. There is a minimum width that can not change for some reason, and setting the glow width larger does this
. According to other stackoverflow questions maskNodes are either 1 or 0 in alpha. This is confusing since the SKShapeNode can have different line/glow widths.
Attempt 3. After some research, I discovered I might be able to use the clipping effect and preserve line width/glow using an SKEffectNode instead of SKCropNode.
//Not the exact code to what I tried, but very similar
let maskNode = SKEffectNode()
maskNode.filter = customLinearImageFilter
maskNode.addChild(line)
This produced the (literally) exact same effect as attempt 1. It created the same lines and animation, but the same bugs with other nodes/fps/nodeCount occured. So it seems to be a bug with SKEffectNode, and not SKShapeNode.
I do not know how to bypass the bugs with attempt 1/3 or 2.
Does anybody know if there is something I am doing wrong, if there is a bypass around this, or a different solution altogether for my problem?
Edit: I considered emitters, but there could potentially be hundreds of comets/other nodes coming in within a few seconds and didn't think they would be feasible performance-wise. I have not used SpriteKit before this project so correct me if I am wrong.
This looks like a problem for a custom shader attached to the comet path. If you are not familiar with OpenGL Shading Language (GLSL) in SpriteKit it lets you jump right into the GPU fragment shader specifically to control the drawing behavior of the nodes it is attached to via SKShader.
Conveniently the SKShapeNode has a strokeShader property for hooking up an SKShader to draw the path. When connected to this property the shader gets passed the length of the path and the point on the path currently being drawn in addition to the color value at that point.*
controlFadePath.fsh
void main() {
//uniforms and varyings
vec4 inColor = v_color_mix;
float length = u_path_length;
float distance = v_path_distance;
float start = u_start;
float end = u_end;
float mult;
mult = smoothstep(end,start,distance/length);
if(distance/length > start) {discard;}
gl_FragColor = vec4(inColor.r, inColor.g, inColor.b, inColor.a) * mult;
}
To control the fade along the path pass a start and end point into the custom shader using two SKUniform objects named u_start and u_end These get added to the custom shader during initialization of a custom SKShapeNode class CometPathShape and animated via a custom Action.
class CometPathShape:SKShapeNode
class CometPathShape:SKShapeNode {
//custom shader for fading
let pathShader:SKShader
let fadeStartU = SKUniform(name: "u_start",float:0.0)
let fadeEndU = SKUniform(name: "u_end",float: 0.0)
let fadeAction:SKAction
override init() {
pathShader = SKShader(fileNamed: "controlFadePath.fsh")
let fadeDuration:NSTimeInterval = 1.52
fadeAction = SKAction.customActionWithDuration(fadeDuration, actionBlock:
{ (node:SKNode, time:CGFloat)->Void in
let D = CGFloat(fadeDuration)
let t = time/D
var Ps:CGFloat = 0.0
var Pe:CGFloat = 0.0
Ps = 0.25 + (t*1.55)
Pe = (t*1.5)-0.25
let comet:CometPathShape = node as! CometPathShape
comet.fadeRange(Ps,to: Pe) })
super.init()
path = makeComet...(...) //custom method that creates path for comet shape
strokeShader = pathShader
pathShader.addUniform(fadeStartU)
pathShader.addUniform(fadeEndU)
hidden = true
//set up for path shape, eg. strokeColor, strokeWidth...
...
}
func fadeRange(from:CGFloat, to:CGFloat) {
fadeStartU.floatValue = Float(from)
fadeEndU.floatValue = Float(to)
}
func launch() {
hidden = false
runAction(fadeAction, completion: { ()->Void in self.hidden = true;})
}
...
The SKScene initializes the CometPathShape objects, caches and adds them to the scene. During update: the scene simply calls .launch() on the chosen CometPathShapes.
class GameScene:SKScene
...
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.name = "theScene"
...
//create a big bunch of paths with custom shaders
print("making cache of path shape nodes")
for i in 0...shapeCount {
let shape = CometPathShape()
let ext = String(i)
shape.name = "comet_".stringByAppendingString(ext)
comets.append(shape)
shape.position.y = CGFloat(i * 3)
print(shape.name)
self.addChild(shape)
}
override func update(currentTime: CFTimeInterval) {
//pull from cache and launch comets, skip busy ones
for _ in 1...launchCount {
let shape = self.comets[Int(arc4random_uniform(UInt32(shapeCount)))]
if shape.hasActions() { continue }
shape.launch()
}
}
This cuts the number of SKNodes per comet from 3 to 1 simplifying your code and the runtime environment and it opens the door for much more complex effects via the shader. The only drawback I can see is having to learn some GLSL.**
*not always correctly in the device simulator. Simulator not passing distance and length values to custom shader.
**that and some idiosyncrasies in CGPath glsl behavior. Path construction is affecting the way the fade performs. Looks like v_path_distance is not blending smoothly across curve segments. Still, with care constructing the curve this should work.

How do I use SpriteKit's SKAction to create a time interval for an SKSpriteNode?

I have a function, basketball. I want to be able to spawn my basketBall node at CGPoint(515,700), the top of the screen, in a regular time interval. The only method I knew that would accomplish waiting a few seconds was sleep(); however, sleep() apparently doesn't allow SpriteNodes to remain on screen, so I need an alternative.
I discovered NSTimeInterval, but I would prefer to refrain from importing Foundation. I think that SKAction allows time to pass through waitForDuration(), but I am very confused as to how that works. Can someone shed some light on SpriteKit's SKAction?
override func didMoveToView(view: SKView) {
let basketBall = SKSpriteNode(imageNamed: "basketball")
let waitForObjects = SKAction.waitForDuration(3)
let basketBallFalls = SKAction.runBlock({
self.Basketball()
})
let action = SKAction.sequence([waitForObjects, basketBallFalls])
SKAction.runAction(action, onChildWithName: "basketball")
SKAction.repeatActionForever(action)
//Basketball()
}
func Basketball(){
basketBall.position = CGPointMake(515, 700)
basketBall.size = CGSizeMake(50, 50)
basketBall.size = CGSize(width: 50.0, height: 50.0)
basketBall.zPosition = 10
basketBall.physicsBody = SKPhysicsBody(circleOfRadius: 25.0)
basketBall.physicsBody?.mass = 0.8
basketBall.physicsBody?.restitution = 0.6
basketBall.physicsBody?.dynamic = true
self.addChild(basketBall)
}
Try to use SKAction.waitForDuration(_:).
Ex. something like this:
let waitDuration = NSTimeInterval(arc4random_uniform(20))
let waitAction = SKAction.waitForDuration(waitDuration)
let ballAction = SKAction.runBlock(self.Basketball) //call your function
runAction(SKAction.sequence([waitAction, ballAction]))
There are two straightforward ways to spawn a new node at a regular interval. They both involve your scene.
The scene's update(_:) method is called every frame, and the argument is the current time. Add an NSTimeInterval property to your scene class which will store the last time you created a basketball. In update(_:), subtract the current time from the last spawn time. If the difference is greater than the interval that you want, spawn a new node and keep the new current time.
Your scene can also run actions, like any other node. SKAction has a waitForDuration(_:) method which creates an action that does, well, exactly what its name says. You can create another action using SKAction.runBlock(_:) which will perform the spawning. Then create a sequence action that runs the delay action followed by the spawn action. Wrap that in a repeatActionForever(_:), and finally tell your scene to run the repeater action.

Any way to speed up gameplay gradually in Swift?

I'm currently working on a game using Spritekit. The game has objects which spawn at the top of the screen and fall towards the player character, and the game ends when the player character collides with any of the objects. I am trying to find a way to gradually speed up gameplay over time to make the game more difficult (i.e. objects fall at normal speed when the game begins, after 5 seconds speed up 50%, after 5 more seconds speed up another 50%, ad infinitum.)
Would I need to use NSTimer to make a countdown to increase the gravity applied to the falling objects? Sorry if this is a basic thing, I'm kind of new to programming.
Thanks, Jake
EDIT:
My spawn method for enemies-
let spawn = SKAction.runBlock({() in self.spawnEnemy()})
let delay = SKAction.waitForDuration(NSTimeInterval(2.0))
let spawnThenDelay = SKAction.sequence([spawn, delay])
let spawnThenDelayForever = SKAction.repeatActionForever(spawnThenDelay)
self.runAction(spawnThenDelayForever)
And my method for making the enemies fall-
func spawnEnemy() {
let enemy = SKNode()
let x = arc4random()
fallSprite.physicsBody = SKPhysicsBody(rectangleOfSize: fallSprite.size)
fallSprite.physicsBody.dynamic = true
self.physicsWorld.gravity = CGVectorMake(0.0, -0.50)
enemy.addChild(fallSprite)
}
In spawnEnemy(), you set self.physicsWorld.gravity. Move this line to your update: method.
If you are not keeping track of the game's duration right now, you will want to implement that. You can use the parameter of the update: method to accomplish this.
You can then use the game duration to change the gravity.
For example,
override func update(currentTime: CFTimeInterval) {
if gameState == Playing{
//update "duration" using "currentTime"
self.physicsWorld.physicsBody = CGVectorMake(0.0, -0.50 * (duration / 10.0))
}
}
10.0 can be changed depending on how fast you want the gravity to increase. A higher number makes it change less drastically, and a smaller number makes the gravity increase quite rapidly.
Hopefully this answers your question.

Spritekit - dynamically adding children slows performance

I'm trying to figure out how to optimize my game. I have a lot of turrets etc shooting out physics bodies. The game is playable but can dip into 50 or 45 fps. I've figured out that it is related to adding objects to my scene on the fly.
for example. when my turret is shooting it runs this code
func shootBlaster(){
let blaster = Projectile(color: SKColor.cyanColor(), size: CGSize(width: convertNum(3), height: convertNum(3)))
blaster.name = "blaster"
blaster.physicsBody = SKPhysicsBody(rectangleOfSize: blaster.size)
blaster.physicsBody!.categoryBitMask = CategoryEnemyProjectile
blaster.physicsBody!.contactTestBitMask = CategoryShip | CategoryShipShield
blaster.physicsBody!.collisionBitMask = 0
let fireAction = SKAction.runBlock({
let angle = self.turret.base.zRotation + self.zRotation
let velocity = CGPoint(angle: angle) * convertNum(420)
let vector = CGVectorMake(velocity.x, velocity.y)
let blas = blaster.copy() as Projectile
blas.wpnDmg = 10
blas.position = self.gameScene.gameLayer.convertPoint(self.turret.barrelPos, fromNode: self.turret.base)
self.gameScene.gameLayer.addChild(blas)
blas.physicsBody!.velocity = vector
blas.zRotation = blas.physicsBody!.velocity.angle
blas.runAction(SKAction.removeFromParentAfterDelay(1))
})
let recoilAction = SKAction.moveByX(-5, y: 0, duration: 0.08)
let reverseRecoil = recoilAction.reversedAction()
self.turret.barrel.runAction(SKAction.repeatAction(
SKAction.sequence([
recoilAction,
fireAction,
reverseRecoil
])
,count: self.blasterNum))
}
you can see that I'm adding a "blaster" inside of each of the fireAction blocks. I've noticed games with better performance are rarely adding children at runtime. It seems best to have everything pre-loaded. It makes sense that loading resources during runtime would put a strain on things, but what is the alternative? Do I need to add everything to the scene ahead of time and somehow hide and show it?
With any kind of shooting game where you have numerous projectiles you want to utilize "pooling". Create a pool of projectiles and reuse them as opposed to creating new ones when you need them.

Random movements / turbulences - SWIFT

I'm developing a game on Iphone and Ipad like a space invaders.
Balloons to destroy are falling from the top of the screen in a straight line.
Here my codes to add them :
func addBalloonv(){
var balloonv:SKSpriteNode = SKSpriteNode (imageNamed: "ballonvert.png")
balloonv.physicsBody = SKPhysicsBody (circleOfRadius: balloonv.size.width/2)
balloonv.physicsBody.dynamic = true
balloonv.physicsBody.categoryBitMask = balloonCategory | greenCategory
balloonv.physicsBody.contactTestBitMask = flechetteCategory
balloonv.physicsBody.collisionBitMask = balloonCategory
balloonv.physicsBody.mass = 1
balloonv.physicsBody.restitution = 1
balloonv.physicsBody.allowsRotation = true
let minX = balloonv.size.width/2
let maxX = self.frame.size.width - balloonv.size.width/2
let rangeX = maxX - minX
let position:CGFloat = CGFloat(arc4random()) % CGFloat(rangeX) + CGFloat(minX)
balloonv.position = CGPointMake(position, self.frame.size.height+balloonv.size.height)
self.addChild(balloonv)
I have one func by balloon color.
So for the moment they move in straight line and I'm looking for random movements (with turbulences like balloon in air) from the top and both sides.
How can I do that?
Thank you very much !!
This is exactly what the new Physics Fields feature in SpriteKit (as of iOS 8 / OS X Yosemite) is for. These let you apply different kinds of forces to all physics bodies in region, like gravity, drag, and turbulence. See the SKFieldNode class docs for details.
Fields are a kind of node, so to get what you're after, you'd add one noise (or turbulence) field to your scene, covering the area that the balloons fall through, and it'll perturb the path of each balloon that passes. The simplest way to do it goes something like this:
let field = SKFieldNode.noiseFieldWithSmoothness(0.5, animationSpeed: 0.1)
scene.addChild(field)
You'll want to tweak the smoothness, animation speed, and field.strength till you get just the level of noise you want. You might also look into whether you want just a noise field, which applies random forces in random directions, or a turbulence field, which does the same thing, but with forces that get stronger when bodies are moving faster.
The above code gets you a field whose region of effect is infinite. You might want to limit it to a specific area (for example, so it doesn't keep knocking your balloons around after they land). I did this to make a field that covers only the top 3/4 of a 300x200 scene:
field.region = SKRegion(size: CGSize(width: 300, height: 100))
field.position = CGPoint(x: 150, y: 150)

Resources