Stop an action until all gameobjects have stopped colliding with barrier - sprite-kit

So far in my code there is a collision detection method that sences when a certain sprite has hit a barrier, and there is also an action sequence I have implemented. In the action sequence I want there to be a wait period where the action stops until a certain amount of sprites have hit the ground (barrier). I've so far got the rotation and cubes falling and the main cube sprite, but the problem I'm trying to solve is getting the cube to stop rotating until all the cubes has hit the barrier. Basically stopping an action until a certain amount of projectile objects has collided with something, then continuing the action. Also the spawning of the cubes is part of the action sequence, so idk what to do without creating clutter in my code.
Please find the below code for reference.
class GameScene:SKScene {
var wait:NSTimeInterval = 0
var blocks = 0
var cube = SKSpriteNode(imageNamed: "cube")
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == barrierCategory && secondBody.categoryBitMask == objectCategory {
secondBody.node?.removeFromParent()
counterTest++
print("hello")
}
if (firstBody.categoryBitMask == blockCategory && secondBody.categoryBitMask == barrierCategory) {
blocks++
}
}
override func didMoveToView(view: SKView) {
NSLog("Start") //Using NSLog just to print the current time
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(interval!), target: self, selector: Selector("spawnBlocks"), userInfo: nil, repeats: false)
cube.runAction(recursive())
}
}
func recursive(){
let recursive = SKAction.sequence([
//SHOULD SPAWN ABOUT 10 BLOCKS
SKAction.spawnBlocks,
//WAIT UNTIL THE COLLISION HAS DETECTED 10 BLOCKS HIT THE BARRIER
SKAction.waitForDuration(waitTime),
//CONTINUE THE ROTATION OF THE CUBE SPRITE
SKAction.rotate,
SKAction.runBlock({[unowned self] in NSLog("Block executed"); self.recursive()})
])
runAction(recursive, withKey: "aKey")
}
}

You don't need your action to be recursive. this makes the logic hard to flow and is unnecessary.
If your cube has a continuous and autonomous behaviour, it should manage it itself in a subclass of SKSprite.
I would suggest you create a rotating action and run it "forever" on your cube. Use removeActionWithName when you want it to stop. Add it again when you want the rotation to resume. This will enable you to implement an easy to use "startRotating" / "stopRotating" pair of functions that you can call whenever appropriate.
Same thing with the cube's continuous behaviour, place it in a runBlock action that repeats forever and start/stop other actions when conditions are met.
This will keep all the cube's behaviour within its own class (preferably in a separate file) and avoid you SKView from becoming a big unmanageable blob of code.

Related

How to detect a Score Node that is moving Fast

Updated my Code below.
I am trying to detect an SKNode that is used to track the score. It is the child of the obstacle that moves right to left on the screen so it moves with the obstacle Node.
The problem is that I can't detect the collision with the score node after a certain speed. In my game the speed increases every time the score node is contacted and it works up to a certain speed and then the collision with the score node is not detected.
I have tried using the usesPreciseCollisionDetection = true but get the same problem.
I need to increase the speed of the obstacles and reduce the wait time between spawning the next obstacle.
what ends up happing with some of my previous attempts, where I increase the speed every time the score node is contacted, is the speed increases but the spawning time doesn't decrease so it creates a gap because the obstacle moves fast enough and goes off screen and the next one isn't spawned yet.
this is the code for the increase speed when contact score node
var speedOfObstacle = 3.0
var speedOfSpawn = 1.0
override func didMove(to view: SKView) {
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.run(SKAction.repeatForever(
SKAction.sequence([
SKAction.run(self.addObstacle),
SKAction.wait(forDuration: self.speedOfSpawn)
])
))
}
}
//** The above SKAction.wait(forDuration: self.speedOfSpawn) determines the spawn time or delay from repeating this sequence. I need to decrease this speedofSpawn But it doesn't change from initial amount of 1.0
func addObstacle() {
//Obstacle Code. Implement the SpeedofObstale.
}
func didBegin(_ contact: SKPhysicsContact) {
var dogBody: SKPhysicsBody
var otherBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
dogBody = contact.bodyA
otherBody = contact.bodyB
} else {
dogBody = contact.bodyB
otherBody = contact.bodyA
}
if dogBody.categoryBitMask == dogSpriteCategory && otherBody.categoryBitMask == obstacleCategory {
// print("dog hit obstacle")
} else if dogBody.categoryBitMask == dogSpriteCategory && otherBody.categoryBitMask == scoreCategory {
print("dog hit score")
score += 1
scoreLabelNode.text = String(score)
if speedOfObstacle >= 0.7 {
speedOfObstacle -= 0.03
print("speed of obstacle is \(speedOfObstacle)")
speedOfSpawn -= 0.01
print("speed of spawn \(speedOfSpawn)")
}
}
}
with the contact score node code the speedOfObstacle decreases from the 3.0 but the wait time for speedOfSpawn does not change from the initial amount of 1.0 .
The speedOfObstacle is used in the addObstacle func, didBegin(_contact), and the viewDidLoad. . The speedOfSpawn is used in the didBegin(_contact) and the viewDidLoad.
Any help on how I can either detect the score node collision at high speed or any way to increase the speed of the obstacle and the frequency of spawning the obstacle would be appreciated.
Thank you,
Updated Code. As answered by bg2b.
I have changed my code and below is what I changed.
enter code here
//replaced the repeat for ever code in view did load with
override func didMove(to view: SKView) {
let initialDelay = 1.0
run(SKAction.sequence([.wait(forDuration: initialDelay), .run { self.addObstacle() }]))
}
// then added this in the addObstacle func
//obstacle physics
//obstacle movement
addChild(obstacle)
let nextDelay = speedOfSpawn
run(SKAction.sequence([.wait(forDuration: nextDelay), .run { self.addObstacle() }]))
and put this in the did begin contact. // same as above just two if statements instead of one.
the speedOfSpawn and speedOfObstacle are declared at the top.
score += 1
scoreLabelNode.text = String(score)
scoreLabelNode.physicsBody?.usesPreciseCollisionDetection = true
if speedOfObstacle >= 1.0 {
speedOfObstacle -= 0.09
print("speed of obstacle is \(speedOfObstacle)")
}
if speedOfSpawn >= 0.40 {
speedOfSpawn -= 0.03
print("speed of spawn \(speedOfSpawn)")
}
I'm not sure about the collision issues, but for the spawning, you're making an action in didMove and then not altering that action. That is, when you write
SKAction.wait(forDuration: self.speedOfSpawn)
you're creating an SKAction that waits for a number of seconds given by the expression self.speedOfSpawn. But if you then change speedOfSpawn, the constructed action isn't made again. If you want to do something with a varying delay, one way is to not do a repeatForever but to put the scheduling of each repetition within the action that is repeating. E.g.,
func spawn() {
// spawn an enemy
...
// schedule next spawn
let nextDelay = ... // some computation of when to spawn next
run(SKAction.sequence([.wait(forDuration: nextDelay), .run { self.spawn() }]))
}
override func didMove(to view: SKView) {
let initialDelay = 1.0
run(SKAction.sequence([.wait(forDuration: initialDelay), .run { self.spawn() }]))
}
Here is another way you can control your spawning. It eliminates the need for a "speedOfSpawn" variable, and instead use the internal timing mechanics. You basically are making the spawn action go faster and faster.
override func didMove(to view: SKView) {
self.run(SKAction.repeatForever(
SKAction.sequence([
SKAction.run(self.addObstacle),
SKAction.wait(forDuration: 1.0)
])
,forKey:"Spawning")
}
func didBegin(_ contact: SKPhysicsContact) {
var dogBody: SKPhysicsBody
var otherBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
dogBody = contact.bodyA
otherBody = contact.bodyB
} else {
dogBody = contact.bodyB
otherBody = contact.bodyA
}
if dogBody.categoryBitMask == dogSpriteCategory && otherBody.categoryBitMask == obstacleCategory {
// print("dog hit obstacle")
} else if dogBody.categoryBitMask == dogSpriteCategory && otherBody.categoryBitMask == scoreCategory {
print("dog hit score")
score += 1
scoreLabelNode.text = String(score)
if speedOfObstacle >= 0.7 {
speedOfObstacle -= 0.03
print("speed of obstacle is \(speedOfObstacle)")
self.action(forKey:"Spawning")?.speed += 0.01
}
}
}
The problem with collision is you are essentially playing God when you use SKAction's.
I would recommend using the physics velocity to move your object, not SKActions.
You are also using precision on your scoreLabelNode ..... I believe you want to use the parent's node, since that should have the physics body on it.

How do I choose which node I want to contact with, when a collision happens with two nodes at once with SpriteKit?

I have a an iOS app coded in Swift 3 where a ball is shot and bounces off of bricks on the screen. If I have the brick being one PhysicsBody (a rectangle), I can't easily determine which side/corner of the brick is being hit. What I decided to do instead of this, is have each side of the brick be its own separate node. The issue I am having now, is that a ball can't be in contact with two nodes (say the left and bottom) at once. I am decreasing the value of the brick after every contact with the ball, which in turn is decreasing the value by 2 for this one hit. How can I make it so that if a ball hits two nodes, only execute code for one contact?
Sometimes the below code gets executed twice, with the ball contacting with two brickNodes both times.
func didBegin(_ contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
let countPoint = true
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & ballCategory) != 0 {
if (firstBody.node != nil && secondBody.node != nil){
if (secondBody.categoryBitMask & brickCategory) != 0 {
ballDidHitBrick(ballNode: firstBody.node as! SKShapeNode, brickNode: secondBody.node as! SKShapeNode, decreasePoint: countPoint)
} else if (secondBody.categoryBitMask & roofCategory) != 0 || (secondBody.categoryBitMask & rightWallCategory) != 0 || (secondBody.categoryBitMask & leftWallCategory) != 0 || (secondBody.categoryBitMask & bottomCategory) != 0 {
ballDidHitWall(ballNode: firstBody.node as! SKShapeNode, wallNode: secondBody.node as! SKShapeNode)
} else {
//Nothing as of yet
}
}
}
}
So going along with what Steve has said above, I implemented the code below and I am no longer having dual contacts per update:
if !bricksHit.contains("\(secondBody.node?.name ?? ""), \(firstBody.node?.name ?? "")") {
//If ball hasnt hit the object more than once
bricksHit.append("\(secondBody.node?.name ?? ""), \(firstBody.node?.name ?? "")")
ballDidHitBrick(ballNode: firstBody.node as! SKShapeNode, brickNode: secondBody.node as! SKShapeNode, decreasePoint: countPoint, contact: contact)
}
I also added in the below to my code, which clears the bircksHit after every update:
override func didFinishUpdate() {
bricksHit.removeAll()
}
I would scrap the multiple nodes with multiple bodies, that would yield terrible performance if you have many blocks.
Instead, you should process your work in steps.
During your didBegin phase, you need to keep track of where the contact point is. This can be done with userData
func didBegin(_ contact: SKPhysicsContact) {
var firstBody:SKPhysicsBody
var secondBody:SKPhysicsBody
let countPoint = true
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & ballCategory) != 0, (secondBody.categoryBitMask & brickCategory) != 0 {
let userData = firstBody.node!.userData ?? [String,AnyObject]()
let contactPoints = userData["contactPoints"] as? [CGPoint] ?? [CGPoint]()
contactPoints.append(contact.contactPoint) //if need be add other info like the vector or relative to the node
userData["contactPoints"] = contactPoints
}
}
Then in a process later on, like didSimulatePhysics You can evaluate the nodes that were contacted, determine the priority of contact (like the bottom would supersede the sides, or if the velocity x > velocity y, sides, whatever you need to do) and react in this manner.
Note this is only sample code, it will not work verbatim. You will need to structure it into your code to get it to properly work.
Yep - this happens. The consensu of opinion seems to be that if there are multiple simultaneous contact points between 2 physics bodies, SK will call didBegin for every contact point, resulting in multiple calls (in the sam game loop) for the same pair of physics bodies.
The way to handle it (you can't get sprite-kit to NOT call didBegin multiple times in some circumstances) is to make sure that your contact code accommodates this and that handling the contract multiple times does not cause a problem (such as adding to the score multiple times, removing multiple lives, trying to access a node or physicsBody that has been removed etc).
Some things you can do include:
If you remove a node that is contacted, check for it being nil before
you remove it (for the duplicate contacts)
Add the node to a set and then remove all the nodes in the set in didFinishUpdate
Add an 'inactive' flag' to the node's userData
Make the node a subclass of SKSpriteNode and add an 'inactive' property (or similar)
Etc etc.
See this question and answer about SK calling didBegin multiple times for a single contact:
Sprite-Kit registering multiple collisions for single contact
Also SKPhysicsContact contains not only details of the 2 physics bodies that have collided, but also the contact point. From this, and the position properties of the 2 nodes involved, you could indeed calculate which side/corner of the brick is being hit.

app crashing after trying to load an skspritenode twice?

I asked a question before and i wound up deleting it as i though i figured it out, but i actually just narrowed it down.
When one of my nodes hits into an obstacle, the game presents a score label and a restart button. But if my node hits a different object after the initial hit, the app crashes. If i run the game with // in front of the the label and restart to take them out of the equation the game runs fine, but if i run the game with them, it crashes.
This leads me to believe its crashing because its trying to load the restart button and score label twice. I might be totally wrong but how can i correct this?
I think you're probably right.
Trying to addchild is how I presume you're adding things to the scene. If you try to add something to a scene or object that's already added to a something, you get a crash.
So you're probably trying to add your restart and score label to something, as a child, when they already have a parent, and this is causing the crash.
SOLVED IT!
I added if statements to make the app only run my collision code after 1 collision and not 2
var collision = Int()
func didBegin(_ contact: SKPhysicsContact) {
var firstBody : SKPhysicsBody = contact.bodyA
var secondBody : SKPhysicsBody = contact.bodyB
if collision == 0{
if ((firstBody.categoryBitMask == physicsCatagory.bird) && (secondBody.categoryBitMask == physicsCatagory.obstacle)) {
collisionWithObstacle(bird: firstBody.node as! SKSpriteNode)
}
}
else if collision != 0{
if ((firstBody.categoryBitMask == physicsCatagory.bird) && (secondBody.categoryBitMask == physicsCatagory.obstacle)) {
}
}
}
func collisionWithObstacle(bird:SKSpriteNode){
collision = collision+1
scoreTimer.invalidate()
obstacleTimer.invalidate()
addChild(restart)
scoreLabel2.text = "Score: \(score1)"
addChild(scoreLabel2)
}
hope this can help someone else because although it seems trivial in hindsight, it was a head scratcher for a few nights after work.

Changing the location of a node once the location is already set.(SpriteKit)

I am working on a game that involves objects(fish) that move across the screen that you need to catch with another object(hook) that you can move up and down. Once the objects make contact the fish's position is supposed to become the same as the hook's. So in did begin contact (which does work, Im sure) I said, when the hook and fish touch make the fishes position become the same as the hooks.
func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
if firstBody.categoryBitMask == physicsCategory.fishHook && secondBody.categoryBitMask == physicsCategory.greenFish || firstBody.categoryBitMask == physicsCategory.greenFish && secondBody.categoryBitMask == physicsCategory.fishHook{
CollisionWithfishHook(firstBody.node as! SKSprit
eNode, greenFish: secondBody.node as! SKSpriteNode)
}
}
func CollisionWithfishHook (fishHook: SKSpriteNode, greenFish: SKSpriteNode){
greenFish.position = CGPointMake(fishHook.position.x, fishHook.position.y)
}
For some reason when I run it and they make contact nothing happens. I know that did begin contact is working correctly because when I told it to remove the fish when it touches the hook it works. The problem is I am unable to change the location of the green fish. Why is this and what can I do to fix it?
Changing the position of the fish in the didBeginContact method is only going to change the fish's position once - the moment the fish and hook touch. You need to continue updating the fish's position in the update method.
I would create a class variable in your GameScene class called fishToUpdate and when you 'hook' one, set fishToUpdate = greenFish (or whatever was caught) in your didBeginContact method. Then in the update method, update the fish's position by fishToUpdate.position = fishHook.position.

Swift - Random collisions are not detected

In my game, I use SKSprite. Some collisions are not detected. I did 10 tries, collisions are working well but about 25% of collisions that are supposed to be detected are not detected. I have NO idea why, I tried many things. Collisions are only with nodes of the same category.
I have no idea why randomly some collisions are not made when I can obviously see them, do you have any idea? Thanks for your help.
Here is the code of didBeginContact:
func didBeginContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
if firstBody.categoryBitMask == secondBody.categoryBitMask {
listContacts.append([firstBody.node!,secondBody.node!])
}
}
}
Here is the code of didEndContact:
func didEndContact(contact: SKPhysicsContact) {
var firstBody: SKPhysicsBody = contact.bodyA
var secondBody: SKPhysicsBody = contact.bodyB
if contact.bodyA.categoryBitMask == contact.bodyB.categoryBitMask {
for i in listContacts{
if (i.contains(firstBody.node!) && i.contains(secondBody.node!)){
let findIndex = listContacts.indexOf { $0 == i }
listContacts.removeFirst(findIndex!)
}
}
}
Finally when I declare a new SKSpriteNode I set this:
rectangle.physicsBody = SKPhysicsBody(rectangleOfSize: rectangle.size)
rectangle.physicsBody?.dynamic = true
rectangle.physicsBody?.collisionBitMask = PhysicsCategory.None
usesPreciseCollisionDetection = true doesn't change anything so I don't use usePrecisionCollisionDetection
Every SKSpriteNode has his categoryBitmask and contactTestBitmask equal because only same SKSpriteNodes are supposed to collide.
Also:
physicsWorld.gravity = CGVectorMake(0, 0)
physicsWorld.contactDelegate = self
Finally here is a short video of my game if you want to understand easily what happens (problem of collisions are between rectangles) https://www.youtube.com/watch?v=-pbmKwQiE9U
You seem to be checking if the categoryBitMask of body A equals body B.
if firstBody.categoryBitMask == secondBody.categoryBitMask {
listContacts.append([firstBody.node!,secondBody.node!])
}
}
This will only run an action if a node hits a node with the same categoryBitMask
You should be checking the collisionBitMasks to see if you have a collision, or you can check the name.
For an example using categoryBitMask you can do something like this:
func didBeginContact(contact: SKPhysicsContact) {
var sprite: SKSpriteNode!
if contact.bodyA.categoryBitMask == <your category bitmask> {
sprite = contact.bodyA.node! as! SKSpriteNode
}
else if contact.bodyB.categoryBitMask == <your category bitmask> {
sprite = contact.bodyB.node! as! SKSpriteNode
}
// Do something with sprite....
// You can also create another sprite, and assign it to the other body, and perform functions on it, or both A and B.
// It is good to have different functions you send can send the nodes to once you find out which ones they are.
}
You can do these checks to see which sprites are hitting each other.
I just fixed it! The reason was that in the function "touchesEnded", I had a recursive function that was deleting bad connections in the listContacts!