Collision detection inconsistent - swift

My collision detection is working most of the time, but sometimes one physics body will go inside the other, when they should collide. I have a car with physics and road sides with physics. The car will blow through the road sides occasionally. I'm moving the car forward by position, however I have also tried moving forward by force and the same thing happens. Does anyone have any idea what would be causing this?
I've defined my physics categorys like so;
struct PhysicsCategory: OptionSet {
let rawValue: UInt32
init(rawValue: UInt32) { self.rawValue = rawValue }
static let CarCategory = PhysicsCategory(rawValue: 0b00001)
static let RoadSidesCategory = PhysicsCategory(rawValue: 0b00010)
static let NoCollisionsCategory = PhysicsCategory(rawValue: 0b00000)
}
Giving the car physics like so;
func giveCarPhysics(physics: Bool) {
//give physicsBody to the car and set to collide with the background
if physics {
self.size = CGSize(width: self.size.width, height: self.size.height)
self.physicsBody = SKPhysicsBody(rectangleOf: CGSize (width: self.size.width * 0.6, height: self.size.height * 0.9), center: CGPoint(x: self.anchorPoint.x, y: self.anchorPoint.y + self.size.height / 2))
self.physicsBody?.mass = vehicleMass
self.physicsBody?.usesPreciseCollisionDetection = true
self.physicsBody?.friction = 0.5
self.physicsBody?.restitution = 0.2
self.physicsBody?.affectedByGravity = false
self.physicsBody?.isDynamic = true
self.physicsBody?.linearDamping = airResistance
self.physicsBody?.categoryBitMask = PhysicsCategory.CarCategory.rawValue
self.physicsBody?.collisionBitMask = PhysicsCategory.RoadSidesCategory.rawValue
self.physicsBody?.contactTestBitMask = PhysicsCategory.RoadSidesCategory.rawValue
}
}
And then giving the road sides physics;
func createPhysicsRight() {
for (index, backgroundImageRight) in self.physicsRight.enumerated() {
let roadSpriteR = SKSpriteNode()
roadSpriteR.anchorPoint = CGPoint(x: 0.5, y: 0.5)
roadSpriteR.position = CGPoint(x: 0, y: CGFloat(self.physicsCounterR) * self.frame.size.height)
roadSpriteR.zPosition = 0
roadSpriteR.name = "RoadR \(index)"
print(roadSpriteR.name as Any)
roadSpriteR.physicsBody = SKPhysicsBody(polygonFrom: backgroundImageRight)
roadSpriteR.physicsBody?.mass = backgroundMass
roadSpriteR.physicsBody?.affectedByGravity = false
roadSpriteR.physicsBody?.isDynamic = false
roadSpriteR.physicsBody?.categoryBitMask = PhysicsCategory.RoadSidesCategory.rawValue
roadSpriteR.physicsBody?.collisionBitMask = PhysicsCategory.CarCategory.rawValue
roadSpriteR.physicsBody?.contactTestBitMask = PhysicsCategory.CarCategory.rawValue
roadSpriteRArray.append(roadSpriteR)
}
}
func createPhysicsLeft() {
for (index, backgroundImageLeft) in self.physicsLeft.enumerated() {
let roadSpriteL = SKSpriteNode()
roadSpriteL.anchorPoint = CGPoint(x: 0.5, y: 0.5)
roadSpriteL.position = CGPoint(x: 0, y: CGFloat(self.physicsCounterL) * self.frame.size.height)
roadSpriteL.zPosition = 0
roadSpriteL.name = "RoadL \(index)"
roadSpriteL.physicsBody = SKPhysicsBody(polygonFrom: backgroundImageLeft)
roadSpriteL.physicsBody?.mass = backgroundMass
roadSpriteL.physicsBody?.affectedByGravity = false
roadSpriteL.physicsBody?.isDynamic = false
roadSpriteL.physicsBody?.categoryBitMask = PhysicsCategory.RoadSidesCategory.rawValue
roadSpriteL.physicsBody?.collisionBitMask = PhysicsCategory.CarCategory.rawValue
roadSpriteL.physicsBody?.contactTestBitMask = PhysicsCategory.CarCategory.rawValue
roadSpriteLArray.append(roadSpriteL)
}
}

Related

Not detecting collision - SpriteKit - Swift

I am trying to detect collision between 2 objects but it works only some times. Most of the time it doesn't work. Maybe you can help me out understanding what i am doing wrong.
static let soldier: UInt32 = 0x1 << 4
static let enemy: UInt32 = 0x1 << 5
function setting the physicsBody for the ground, the soldier and the enemy:
func addPhysicsBody(to sprite: SKSpriteNode, with name: String) {
let centerPoint = CGPoint(x:sprite.size.width / 2 - (sprite.size.width * sprite.anchorPoint.x), y:sprite.size.height / 2 - (sprite.size.height * sprite.anchorPoint.y))
sprite.physicsBody = SKPhysicsBody(rectangleOf: sprite.size, center: centerPoint)
sprite.physicsBody?.allowsRotation = false
sprite.physicsBody?.affectedByGravity = true
sprite.physicsBody?.restitution = 0.0
sprite.physicsBody?.friction = 0
if name.contains(GameConstants.StringConstants.soldierName) {
sprite.physicsBody?.categoryBitMask = GameConstants.PhysicsCategories.soldier
sprite.physicsBody?.contactTestBitMask = GameConstants.PhysicsCategories.enemy
sprite.physicsBody?.collisionBitMask = GameConstants.PhysicsCategories.ground
sprite.physicsBody?.isDynamic = true
} else if name.contains(GameConstants.StringConstants.enemyName) {
sprite.physicsBody?.categoryBitMask = GameConstants.PhysicsCategories.enemy
sprite.physicsBody?.contactTestBitMask = GameConstants.PhysicsCategories.soldier
sprite.physicsBody?.collisionBitMask = GameConstants.PhysicsCategories.ground
sprite.physicsBody?.isDynamic = true
} else if name == GameConstants.StringConstants.groundName {
sprite.physicsBody?.affectedByGravity = false
sprite.physicsBody?.categoryBitMask = GameConstants.PhysicsCategories.ground
sprite.physicsBody?.isDynamic = false
}
}
generating the soldier and the enemy and moving them:
func generateASoldier() {
let soldier = SKSpriteNode(texture: SKTexture(image: UIImage(named: "0\(GameConstants.StringConstants.idlePrefixKey)0")!), color: UIColor.darkGray, size: self.frame.size)
soldier.size = CGSize(width: castle.frame.size.height/4, height: castle.frame.size.height/4)
soldier.name = "\(GameConstants.StringConstants.soldierName)\(soldierCounter)"
soldierCounter+=1
addPhysicsBody(to: soldier, with: soldier.name!)
soldier.position = CGPoint(x: frame.minX-soldier.size.width*2, y: frame.midY/1.1)
soldier.zPosition = GameConstants.ZPositions.playerZ
addChild(soldier)
isMovingSoldier.append(true)
moveSoldier(soldier: soldier, index: isMovingSoldier.count-1)
}
func moveSoldier(soldier: SKSpriteNode, index: Int) {
soldier.physicsBody?.applyImpulse(CGVector(dx: charactersSpeed, dy: 0))
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
if self.isMovingSoldier[index] {
self.moveSoldier(soldier: soldier, index: index)
}
})
}
func generateAnEnemy() {
let enemy = SKSpriteNode(texture: SKTexture(image: UIImage(named: "1\(GameConstants.StringConstants.idlePrefixKey)0")!), color: UIColor.darkGray, size: self.frame.size)
enemy.size = CGSize(width: -castle.frame.size.height/4, height: castle.frame.size.height/4)
enemy.name = "\(GameConstants.StringConstants.enemyName)\(enemyCounter)"
enemyCounter+=1
addPhysicsBody(to: enemy, with: enemy.name!)
enemy.position = CGPoint(x: frame.maxX-enemy.size.width*2, y: frame.midY/1.1)
enemy.zPosition = GameConstants.ZPositions.playerZ
addChild(enemy)
isMovingEnemy.append(true)
moveEnemy(enemy: enemy, index: isMovingEnemy.count-1)
}
func moveEnemy(enemy: SKSpriteNode, index: Int) {
enemy.physicsBody?.applyImpulse(CGVector(dx: -charactersSpeed, dy: 0))
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
if self.isMovingEnemy[index] {
self.moveEnemy(enemy: enemy, index: index)
}
})
}
generating the ground:
func generateGround() {
ground = SKSpriteNode(color: .white, size: CGSize(width: frame.maxX*3, height: UIScreen.main.bounds.size.height/2.435))
ground.name = GameConstants.StringConstants.groundName
addPhysicsBody(to: ground, with: ground.name!)
ground.zPosition = GameConstants.ZPositions.playerZ
ground.position = CGPoint(x: frame.midX, y: frame.minY)
self.addChild(ground)
}
Using this code func didBegin(_ contact: SKPhysicsContact) is called a random amount of times and i am trying to make sure it will be called every time the soldier and the enemy collide
Edit:
I found out that the problem is detecting the collision using the applyImpulse function. Using gravity it detects the collision

How to prevent Sprite Nodes from pushing each other?

3 Sprite Nodes are moving up at different speed levels. You see that the gorilla likes to rest, but the lobster is pushing it slowly upwards. Expected behaviour would be, that the lobster would rest also and continue going upwards when the gorilla starts moving again. Using .isDynamic = false did not work — the Sprite Nodes were overlaying and lobster ignored the physical body of the hedgehog and the gorilla totally.
Recording of my Playground Scene: https://youtu.be/l47kaJiJvkM
Screenshot of the video:
Code:
import SpriteKit
public class WalkingScene: SKScene {
public override func didMove(to view: SKView) {
backgroundColor = .white
view.showsPhysics = true
let hedgehog = SKSpriteNode(imageNamed: "hedgehog")
hedgehog.size = CGSize(width: 64, height: 64)
hedgehog.position = CGPoint(x: size.width/2, y: 400)
hedgehog.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 80, height: 80))
hedgehog.physicsBody?.affectedByGravity = false
hedgehog.physicsBody?.allowsRotation = false
let gorilla = SKSpriteNode(imageNamed: "gorilla")
gorilla.size = CGSize(width: 64, height: 64)
gorilla.position = CGPoint(x: size.width/2, y: 140)
gorilla.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 80, height: 80))
gorilla.physicsBody?.affectedByGravity = false
gorilla.physicsBody?.allowsRotation = false
let lobster = SKSpriteNode(imageNamed: "lobster")
lobster.size = CGSize(width: 64, height: 64)
lobster.position = CGPoint(x: size.width/2, y: 20)
lobster.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 80, height: 80))
lobster.physicsBody?.affectedByGravity = false
lobster.physicsBody?.allowsRotation = false
// hedgehog.physicsBody?.isDynamic = false
// gorilla.physicsBody?.isDynamic = false
// lobster.physicsBody?.isDynamic = false
// hedgehog.physicsBody?.usesPreciseCollisionDetection = true
// hedgehog.physicsBody?.collisionBitMask = 0
// gorilla.physicsBody?.usesPreciseCollisionDetection = true
// gorilla.physicsBody?.collisionBitMask = 0
// lobster.physicsBody?.usesPreciseCollisionDetection = true
// lobster.physicsBody?.collisionBitMask = 0
self.addChild(lobster)
self.addChild(hedgehog)
self.addChild(gorilla)
self.moveGorilla(gorilla)
self.moveLobster(lobster)
self.moveHedgeHog(hedgehog)
}
func moveGorilla(_ passenger: SKSpriteNode) {
let moveLeft = CGVector(dx: 0, dy: 200)
let aYYY = CGVector(dx: 200, dy: 0)
let moving = SKAction.move(by: moveLeft, duration: 1)
let turnAYY = SKAction.move(by: aYYY, duration: 1)
let chill = SKAction.wait(forDuration: 3)
passenger.run(SKAction.sequence([moving, chill, moving, chill, turnAYY])) {
print("Gorilla arrived")
}
}
func moveLobster(_ passenger: SKSpriteNode) {
let moveLeft = CGVector(dx: 0, dy: 200)
let moving = SKAction.move(by: moveLeft, duration: 1.2)
passenger.run(SKAction.sequence([moving, moving, moving, moving, moving, moving, moving, moving, moving])) {
print("Lobster arrived")
}
}
func moveHedgeHog(_ passenger: SKSpriteNode) {
let moveLeft = CGVector(dx: 0, dy: 200)
let moving = SKAction.move(by: moveLeft, duration: 1)
let chill = SKAction.wait(forDuration: 2)
passenger.run(SKAction.sequence([chill, moving, moving, moving])) {
print("Hedgehog arrived")
}
}
}
You can set those dynamics this way:
hedgehog.physicsBody?.isDynamic = true
gorilla.physicsBody?.isDynamic = false
lobster.physicsBody?.isDynamic = true
By this strategy, you can extend this example to other situations.
If isDynamic = true is treated as 0 , and the isDynamic = false, ie static, treated as infinity,
there is something between which can be controlled by the mass of a physics body.
hedgehog.physicsBody?.isDynamic = false. (mass = Infinity)
gorilla.physicsBody?.isDynamic = true. (mass = big)
lobster.physicsBody?.isDynamic = true (mass = 0)
gorilla.physicsBody?.mass = 1000

How to rotate sprites around a joint

I need to make the arms and hands rotate around the center of the hook, as shown in the image below without them separating or changing their shape (no changes in the angles between arms and hands just rotation at A), as in the image below:
I tried rotating the arms but this made them separate and change form. You can check out my code below:
let hookCategoryName = "hook"
let leftArmCategoryName = "leftArm"
let rightArmCategoryName = "rightArm"
let leftHandCategoryName = "leftHand"
let rightHandCategoryName = "rightHand"
let hookCategory : UInt32 = 0x1 << 0
let leftArmCategory : UInt32 = 0x1 << 1
let rightArmCategory : UInt32 = 0x1 << 2
let leftHandCategory : UInt32 = 0x1 << 3
let rightHandCategory : UInt32 = 0x1 << 4
extension Int {
var degreesToRadians: Double { return Double(self) * .pi / 180 }
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var hook = SKSpriteNode(imageNamed: "hook")
var leftArm = SKSpriteNode(imageNamed: "arm")
var rightArm = SKSpriteNode(imageNamed: "arm")
var leftHand = SKSpriteNode(imageNamed: "leftHand")
var rightHand = SKSpriteNode(imageNamed: "rightHand")
override func didMove(to view: SKView) {
self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
self.physicsWorld.contactDelegate = self
var yellowBg = SKSpriteNode(imageNamed: "yellowBg")
yellowBg.position = CGPoint(x: frame.midX, y: frame.midY)
yellowBg.zPosition = 2
addChild(yellowBg)
hook.position = CGPoint(x: frame.midX, y: frame.midY + frame.midY/2)
hook.zPosition = 5
hook.name = hookCategoryName
hook.physicsBody = SKPhysicsBody(rectangleOf: hook.frame.size)
hook.physicsBody?.categoryBitMask = hookCategory
hook.physicsBody?.isDynamic = false
addChild(hook)
rightArm.anchorPoint = CGPoint(x: 0.5, y: 1)
rightArm.position = hook.position
rightArm.zPosition = 5
rightArm.name = rightArmCategoryName
rightArm.physicsBody = SKPhysicsBody(rectangleOf: rightArm.frame.size)
rightArm.physicsBody?.categoryBitMask = rightArmCategory
rightArm.physicsBody!.isDynamic = true
addChild(rightArm)
leftArm.anchorPoint = CGPoint(x: 0.5, y: 1)
leftArm.position = hook.position
leftArm.zPosition = 5
leftArm.name = leftArmCategoryName
leftArm.physicsBody = SKPhysicsBody(rectangleOf: leftArm.frame.size)
leftArm.physicsBody?.categoryBitMask = leftArmCategory
leftArm.physicsBody!.isDynamic = true
addChild(leftArm)
// leftHand
leftHand.anchorPoint = CGPoint(x: 0.5, y: 0.5)
leftHand.position = CGPoint(x: leftArm.frame.minX - 22, y: leftArm.frame.minY + 7) //CGPoint(x: armLeft.position.x, y: armLeft.position.y)
leftHand.zPosition = 5
leftHand.name = leftHandCategoryName
leftHand.physicsBody = SKPhysicsBody(rectangleOf: leftHand.frame.size)
leftHand.physicsBody?.categoryBitMask = leftHandCategory
leftHand.zRotation = CGFloat(Double(-30).degreesToRadians)//CGFloat(-Double.pi/6)
//armLeft.physicsBody?.categoryBitMask = armCategory
leftHand.physicsBody!.isDynamic = true
addChild(leftHand)
// rightHand
rightHand.anchorPoint = CGPoint(x: 0.5, y: 0.5)
rightHand.position = CGPoint(x: rightArm.frame.minX + 30, y: rightArm.frame.minY + 7) //CGPoint(x: armLeft.position.x, y: armLeft.position.y)
rightHand.zPosition = 5
rightHand.name = rightHandCategoryName
rightHand.physicsBody = SKPhysicsBody(rectangleOf: rightHand.frame.size)
rightHand.physicsBody?.categoryBitMask = rightHandCategory
rightHand.zRotation = CGFloat(Double(30).degreesToRadians)//CGFloat(-Double.pi/6)
//armLeft.physicsBody?.categoryBitMask = armCategory
rightHand.physicsBody!.isDynamic = true
addChild(rightHand)
leftArm.zRotation = CGFloat(Double(-45).degreesToRadians)
rightArm.zRotation = CGFloat(Double(45).degreesToRadians)
rightHand.physicsBody?.contactTestBitMask = rightHandCategory
leftHand.physicsBody?.contactTestBitMask = leftHandCategory
rightHand.physicsBody?.collisionBitMask = rightHandCategory
leftHand.physicsBody?.collisionBitMask = leftHandCategory
let hookAndRightArmJoint = SKPhysicsJointPin.joint(withBodyA: hook.physicsBody!, bodyB: rightArm.physicsBody!, anchor: CGPoint(x: hook.position.x, y: self.rightArm.frame.maxY))
self.physicsWorld.add(hookAndRightArmJoint)
let hookAndLeftArmJoint = SKPhysicsJointPin.joint(withBodyA: hook.physicsBody!, bodyB: leftArm.physicsBody!, anchor: CGPoint(x: hook.position.x, y: self.leftArm.frame.maxY))
self.physicsWorld.add(hookAndLeftArmJoint)
let armsFixedJoint = SKPhysicsJointFixed.joint(withBodyA: leftArm.physicsBody!, bodyB: rightArm.physicsBody!, anchor: CGPoint.zero)
self.physicsWorld.add(armsFixedJoint)
//left arm and hand joint
let leftArmAndHandJoint = SKPhysicsJointPin.joint(withBodyA: leftArm.physicsBody!, bodyB: leftHand.physicsBody!, anchor: CGPoint(x: self.leftArm.frame.minX, y: self.leftArm.frame.minY)/*CGPoint(x: armLeft.position.x, y: self.armLeft.frame.minY)*/)
self.physicsWorld.add(leftArmAndHandJoint)
//right arm and hand joint
let rightArmAndHandJoint = SKPhysicsJointPin.joint(withBodyA: rightArm.physicsBody!, bodyB: rightHand.physicsBody!, anchor: CGPoint(x: self.rightArm.frame.maxX, y: self.rightArm.frame.minY)/*CGPoint(x: armLeft.position.x, y: self.armLeft.frame.minY)*/)
self.physicsWorld.add(rightArmAndHandJoint)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
hook.run(SKAction.rotate(byAngle: CGFloat(Double(60).degreesToRadians), duration: 0.5))
}
}
Also rotating the hook has no effect on the arms and hands as seen in the image below when the above code is run:
How can I get the rotation in the image first image?
You can make the arms and hands children of a common parent node. You could create a blank SKNode for just this purpose like so:
let armsParent = SKNode()
Then instead of adding the arms and hands as children to the scene directly, add them as children of armsParent like so:
armsParent.addChild(leftArm)
armsParent.addChild(rightArm) // same for hands...
Then you can simply rotate armsParent with an SKAction to achieve what you want.
OR, to make it even simpler, you could just add the arms and hands as children to hook directly like this:
hook.addChild(leftArm) // same for other arm and hands...
Since the arms and hands are children of hook or armParent their positions will now be determined relative to their parent. So you might have to change all your .position = initialization code to accommodate this.

Multiple physics bodies in SpriteKit

I have a 40x40 rectangle node, and I want to detect when the bottom touches a platform.
I tried this
let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 1), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 0.5)))
then set the categoryBitMask, collisionBitMask, contactTestBitMaskand added it to the hero
hero.physicsBody = SKPhysicsBody(bodies: [feet])
But in didBeginContact the println() doesn't print.
I need a body for the bottom of the rectangle and one for the top, because if hero hits a platform from below the collision should push him down.
Update
Here is how I set the bit masks
let heroFeetCategory: UInt32 = 1 << 0
let edgeCategory: UInt32 = 1 << 1
let groundCategory: UInt32 = 1 << 2
let feet = SKPhysicsBody(rectangleOfSize: CGSize(width: hero.frame.size.width, height: 10), center: CGPoint(x: 0, y: -(hero.frame.size.height/2 - 5)))
feet.collisionBitMask = edgeCategory | groundCategory
feet.contactTestBitMask = groundCategory
feet.categoryBitMask = heroFeetCategory
hero.physicsBody = SKPhysicsBody(bodies: [feet])
hero.physicsBody?.usesPreciseCollisionDetection = true
hero.physicsBody?.velocity = CGVectorMake(0, 0)
hero.physicsBody?.restitution = 0.0
hero.physicsBody?.friction = 0.0
hero.physicsBody?.angularDamping = 0.0
hero.physicsBody?.linearDamping = 1.0
hero.physicsBody?.allowsRotation = false
hero.physicsBody?.mass = 0.0641777738928795
world.addChild(hero)
and for the ground
let ground = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(38, 38))
ground.name = "groundName"
ground.position = CGPoint(x: 0, y: -(self.frame.size.height/2 - ground.frame.size.height/2))
ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
ground.physicsBody?.collisionBitMask = edgeCategory | heroFeetCategory
ground.physicsBody?.contactTestBitMask = heroFeetCategory
ground.physicsBody?.categoryBitMask = groundCategory
world.addChild(ground)
And how I detect if they touch
func didBeginContact(contact: SKPhysicsContact) {
var notTheHero: SKPhysicsBody!;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
notTheHero = contact.bodyB;
} else {
notTheHero = contact.bodyA;
}
println(notTheHero.node) // print "heroName"
if (notTheHero.categoryBitMask == groundCategory) {
println("touch began?"); // is never called
}
}
collision is fine, but when you print the node's name through the physics body with notTheHero.node you only access the SKNode, and not the NSString property of its name. Instead, try something like println(notTheHero.node.name);

Use random number (arc4random_uniform) to display random shapes

The purpose for this code is to do random number to display random shapes but the simulator displays them in the same spot which is the bottom left corner of the screen, for some reason the random for the position which is a is not working.
Code:
import UIKit
import SpriteKit
import Darwin
class StartGame: SKScene {
var scoreLabel = SKLabelNode(fontNamed: "cholkDuster")
var square = SKSpriteNode(imageNamed: "square")
var circle = SKSpriteNode(imageNamed: "circle")
var rectangle = SKSpriteNode(imageNamed: "rectangle")
var triangle = SKSpriteNode(imageNamed: "triangle")
let bg = SKSpriteNode(imageNamed: "background.png")
var score = 0
override func didMoveToView(view: SKView) {
//random number for the shapes
var timecreatShapes = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("creatShapes"), userInfo: nil, repeats: true)
//background image
bg.position = CGPoint(x: CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
bg.size.width = self.frame.size.width
bg.size.height = self.frame.size.height
self.addChild(bg)
self.scoreLabel.text = "0"
self.scoreLabel.fontSize = 42
self.scoreLabel.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame))
self.addChild(scoreLabel)
scoreLabel.zPosition = 2
self.physicsWorld.gravity = CGVectorMake(0, -0.5)
//declaring a square image
square.size = CGSize(width: 150, height: 100)
square.color = SKColor.redColor()
square.physicsBody = SKPhysicsBody(circleOfRadius: square.size.height / 2)
square.physicsBody?.dynamic = true
square.physicsBody?.allowsRotation = false
//declaring a circle image
circle.size = CGSize(width: 150, height: 100)
circle.physicsBody = SKPhysicsBody(circleOfRadius: square.size.height / 2)
circle.physicsBody?.dynamic = true
circle.physicsBody?.allowsRotation = false
//declaring a triangle
triangle.size = CGSize(width: 150, height: 100)
triangle.physicsBody = SKPhysicsBody(circleOfRadius: square.size.height / 2)
triangle.physicsBody?.dynamic = true
triangle.physicsBody?.allowsRotation = false
//declaring rectangle
rectangle.size = CGSize(width: 150, height: 100)
rectangle.physicsBody = SKPhysicsBody(circleOfRadius: square.size.height / 2)
rectangle.physicsBody?.dynamic = true
rectangle.physicsBody?.allowsRotation = false
}
func creatShapes () {
var x = Int ( arc4random_uniform(4) + 1)
var a = CGFloat ( arc4random_uniform(1000) + 1)
switch(x){
case 1:
circle.position = CGPoint (x: a , y: self.frame.size.height)
self.addChild(SKSpriteNode(imageNamed:"circle"))
case 2:
square.position = CGPoint(x: a , y: self.frame.size.height)
self.addChild(SKSpriteNode(imageNamed:"square"))
case 3:
rectangle.position = CGPoint(x: a , y: self.frame.size.height)
self.addChild(SKSpriteNode(imageNamed:"rectangle"))
case 4:
triangle.position = CGPoint(x: a , y: self.frame.size.height)
self.addChild(SKSpriteNode(imageNamed:"triangle"))
default:
break
}
println(x)
println(a)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if (self.nodeAtPoint(location) == self.square || self.nodeAtPoint(location) == self.triangle || self.nodeAtPoint(location) == self.circle || self.nodeAtPoint(location) == self.rectangle){
self.score++
}
self.scoreLabel.text = String(self.score)
}
}