I want a game over screen and the game to stop when the screen is touched during a specific animation.
let lightTexture = SKTexture(imageNamed: "green light.png")
let lightTexture2 = SKTexture(imageNamed: "red light.png")
let animateGreenLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1), SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
let changeGreenLight = SKAction.repeatActionForever(animateGreenLight)
let animateRedLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1), SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
let changeRedLight = SKAction.repeatActionForever(animateRedLight)
let greenLight = SKSpriteNode(texture: lightTexture)
greenLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
greenLight.runAction(changeGreenLight)
self.addChild(greenLight)
let redLight = SKSpriteNode(texture: lightTexture2)
redLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
redLight.runAction(changeRedLight)
self.addChild(redLight)
When the animation for the red light is on the screen, I want it to be game over. Do I have to make an if statement, and if so for what specifically?
Thank You in advance!
You can make yourself another node which has the same size and position as the red light. Additionally, that node is able to handle touch events. Then, add that node before the animation runs. This can be done with a sequence of actions, e.g.:
let addAction = SKAction.runBlock({ self.addChild(touchNode) })
let animationAction = SKAction.repeatActionForever(animateRedLight)
redLight.runAction(SKAction.sequence([ addAction, animationAction ]))
Update
Since you want the game to end when you touch anywhere, alter the code such that the block sets a variable which indicates that the animation is executed and implement touchesBegan which checks for that variable, e.g.
let addAction = SKAction.runBlock({ self.redLightAnimationRuns = true })
[...]
// In touchesBegan
if touched
{
if redLightAnimationRuns
{
endGame()
}
}
use the touchesBegan() function to call a GameOver() function when the red light is on the screen (which you can control with a variable).
So, when the red light comes on to the screen, variable redLightCurrent is set to true. in TouchesBegan(), when redLightCurrent is true, then call the gameOver() function where you can include what to do when the game is over. This will only occur when a touch has began on the screen.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let array = Array(touches)
let touch = array[0] as UITouch
let touchLocation = touch.locationInNode(self)
if redLightCurrent {
gameOver()
}
}
This code works with the new xCode 7 and Swift 2.0
Related
I have a car that is a SKShapeNode. It is moving. When I touch it, I want to stop it for 1 second and then go back to movement.
I have this code... But it just stop, a3 is never reached, the car don't start moving again
let a1 = SKAction.speedTo(0.0, duration: 0.0)
let a2 = SKAction.waitForDuration(0.5)
let a3 = SKAction.speedTo(1.0, duration: 0.0)
Here is an example of how to move a node from point A to point B and stop it for one second when touch it.
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
//Create a car
let car = SKSpriteNode(color: UIColor.purpleColor(), size: CGSize(width: 40, height: 40))
car.name = "car"
car.zPosition = 1
//Start - left edge of the screen
car.position = CGPoint(x: CGRectGetMinX(frame), y:CGRectGetMidY(frame))
//End = right edge of the screen
let endPoint = CGPoint(x: CGRectGetMaxX(frame), y:CGRectGetMidY(frame))
let move = SKAction.moveTo(endPoint, duration: 10)
car.runAction(move, withKey: "moving")
addChild(car)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
if let location = touch?.locationInNode(self){
//Get the node
let node = nodeAtPoint(location)
//Check if it's a car
if node.name == "car" {
//See if car is moving
if node.actionForKey("moving") != nil{
//Get the action
let movingAction = node.actionForKey("moving")
//Pause the action (movement)
movingAction?.speed = 0.0
let wait = SKAction.waitForDuration(3)
let block = SKAction.runBlock({
//Unpause the action
movingAction?.speed = 1.0
})
let sequence = SKAction.sequence([wait, block ])
node.runAction(sequence, withKey: "waiting")
}
}
}
}
}
Everything is pretty much commented. So basically, what is happening here is that:
node movement is done by action associated with "moving" key
when user touch the node, action associated by the "moving" key is paused; when this happen, another action called "waiting" is started "in parallel"
"waiting" action waits for one second, and unpause the "moving" action; thus car continue with movement
Currently, when car is touched, the "moving" action is paused...So if you touch the car again, it will stay additional second where it is (the new "waiting" action will overwrite previous "waiting" action). If you don't want this behaviour, you can check if if car is waiting already, like this:
if node.actionForKey("waiting") == nil {/*handle touch*/}
Or you can check if car has stopped by checking the value of speed property of an action associated by the "moving" key.
I have loaded two checkbox sprites on the screen. The image to load the sprite initially in an unchecked checkbox. Then I expect to click on one checkbox and replace the image with another checked checkbox image. The code I have written behaves very strangely where the checked checkbox image never appears.
I have two class properties:
var check1: SKSpriteNode = SKSpriteNode (imageNamed: "unchecked.png")
var check2: SKSpriteNode = SKSpriteNode (imageNamed: "unchecked.png")
I am calling generateCheckboxex() method from didMoveToView(view: SKView)
func generateCheckboxes()
{
self.check1.position = CGPointMake(self.size.width * 0.75, self.size.height * 0.84)
self.check1.setScale(0.15)
self.check1.name = "check1"
self.addChild(self.check1)
self.check2.position = CGPointMake(self.size.width * 0.75, self.size.height * 0.75)
self.check2.setScale(0.15)
self.check2.name = "check2"
self.addChild(self.check2)
}
This is my touchBegan method code:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch = touches as! Set<UITouch>
var location = touch.first!.locationInNode(self)
var node = self.nodeAtPoint(location)
// If next button is touched, start transition to second scene
if node.name == "check1" {
//self.check1.texture = SKTexture(imageNamed: "checked.png")
var texAction = SKAction.setTexture(SKTexture(imageNamed: "checked.png"))
self.check1.runAction(texAction)
//self.check2.texture = SKTexture(imageNamed: "checked.png")
self.check2.runAction(texAction)
}
if node.name == "check2" {
self.check1.texture = SKTexture(imageNamed: "unchecked.png")
self.check2.texture = SKTexture(imageNamed: "checked.png")
}
}
Please help me and let me know if I'm approaching it in the wrong manner, thanks.
EDIT: Admins please close this question, this exact same code works for me now. Maybe it was an issue with the sprites themselves. Thanks!
I want to make a game where every time a user touches, it switches between one of two "states". In order to keep track of touches, I made a variable called userTouches, which changes from true to false each time a user touches. I want to make it so that if numberOfTouches is true, it updates the texture to state0; if it's false, it updates the texture to state1. Pretty much just toggling between state0 and state1 for each touch.
var userTouches: Bool = true
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
userTouches = !userTouches
}
let centered = CGPoint(x: size.width/2, y: size.height/2)
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode = SKSpriteNode(texture: state0)
//Add new state0 if it's odd, remove old state0 if it's not.
if userTouches == true {
activeState.texture = state0
println("IT'S TRUE")
} else {
activeState.texture = state1
println("IT'S FALSE")
}
self.addChild(activeState)
activeState.name = "state0"
activeState.xScale = 0.65
activeState.yScale = 0.65
activeState.position = centered
}
When I run the code, the new textures are added according to the conditions, but the old ones are still there. They are being added as new spritenodes in the scene. I do not want this. I was expecting it to simply switch between the textures (state0 and state1) of the activeState spritenode depending on my boolean variable. How can I have my code toggle between textures each time a user taps, instead of piling new spritenodes on top of one another?
Each time you create a new object, change its texture (a new object`s texture, but not the texture of object which was set up last time) and add it to the scene. That's why new objects are added and nothing happens with the old objects.
Do this and it will solve your problem:
Create textures and SKSpriteNode object outside the touchesBegan function
If you have no init at your scene, create SKSpriteNode object at didMoveToView function for example and add it to scene
Then in touchesBegan function only set texture to SKSpriteNode object
it would look something like this:
class GameScene: SKScene {
...
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode?
...
override func didMoveToView(view: SKView) {
let centered = CGPoint(x: size.width/2, y: size.height/2)
activeState = SKSpriteNode(texture: state0)
self.addChild(activeState!)
activeState!.name = "state0"
activeState!.xScale = 0.65
activeState!.yScale = 0.65
activeState!.position = centered
}
...
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if userTouches {
activeState!.texture = state0
} else {
activeState!.texture = state1
}
}
...
}
I'm coding a game where I have a character following another character and I'd like to make it so that the second character jumps 1 or 2 seconds after the first character jumps. How might I accomplish this?
Here is my method that applies the impulse:
override func touchesBegan(touches: Set, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
fish.physicsBody?.velocity = (CGVectorMake(0,0))
fisherman.physicsBody?.velocity = (CGVectorMake(0,0))
fish.physicsBody?.applyImpulse(CGVectorMake(0, 1000))
fisherman.physicsBody?.applyImpulse(CGVectorMake(0, 3000))
}
}
As you already have follow action, you need just to chain it with delay action. There is a class method waitForDuration that allows you to initialize such Action fast.
Here is a code that will do delay and apply impulse afterward:
for touch in (touches as! Set<UITouch>) {
fish.physicsBody?.velocity = (CGVectorMake(0,0))
fisherman.physicsBody?.velocity = (CGVectorMake(0,0))
let delay = SKAction.waitForDuration(2.0)
let fishApplyImpulse = SKAction.applyImpulse(CGVectorMake(0, 1000),
duration sec: 0.0)
let fishActions = SKAction.sequence([delay, fishApplyImpulse])
let fishermanApplyImpulse = SKAction.applyImpulse(CGVectorMake(0, 3000),
duration sec: 0.0)
let fishermanActions = SKAction.sequence([delay, fishermanApplyImpulse])
fish.runAction(fishActions)
fisherman.runAction(fishermanActions)
}
Code uses SKAction additions for applyImpulse available starting from iOS 9.
I am doing a small for fun project in Swift Xcode 6. The function thecircle() is called at a certain rate by a timer in didMoveToView(). My question is how do I detect if any one of the multiple circle nodes on the display is tapped? I currently do not see a way to access a single node in this function.
func thecircle() {
let circlenode = SKShapeNode(circleOfRadius: 25)
circlenode.strokeColor = UIColor.whiteColor()
circlenode.fillColor = UIColor.redColor()
let initialx = CGFloat(20)
let initialy = CGFloat(1015)
let initialposition = CGPoint(x: initialx, y: initialy)
circlenode.position = initialposition
self.addChild(circlenode)
let action1 = SKAction.moveTo(CGPoint(x: initialx, y: -20), duration: NSTimeInterval(5))
let action2 = SKAction.removeFromParent()
circlenode.runAction(SKAction.sequence([action1, action2]))
}
There are many problems with this.
You shouldnt be creating any looping timer in your games. A scene comes with an update method that is called at every frame of the game. Most of the time this is where you will be checking for changes in your scene.
You have no way of accessing circlenode from outside of your thecircle method. If you want to access from somewhere else you need to set up circlenode to be a property of your scene.
For example:
class GameScene: BaseScene {
let circlenode = SKShapeNode(circleOfRadius: 25)
You need to use the method touchesBegan. It should have come with your spritekit project. You can detect a touch to your node the following way:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
// detect touch in the scene
let location = touch.locationInNode(self)
// check if circlenode has been touched
if self.circlenode.containsPoint(location) {
// your code here
}
}
}