How to Stop Hero (Character) Movement in SpriteKit? - iphone

The main function to walk the Hero this function inside Player.Swift I want to stop walking with Touching position.
This function would be running continues inside GameScene.swift
I want to stop my Hero when user tap to the target Position but after stop Hero whenever user tap on new target location hero moves with new position and stop again.
Here is my code:
{
override init() {
let atlas = SKTextureAtlas(named: "characters")
let texture = atlas.textureNamed("player_ft1")
texture.filteringMode = .Nearest
sprite = AnimatedSprite(texture: texture)
// sprite = SKSpriteNode(texture: texture)
super.init()
addChild(sprite)
name = "player"
// 1
var minDiam = min(sprite.size.width, sprite.size.height)
minDiam = max(minDiam-16.0, 4.0)
let physicsBody = SKPhysicsBody(circleOfRadius: minDiam/2.0)
// 2
physicsBody.usesPreciseCollisionDetection = true
// 3
physicsBody.allowsRotation = false
physicsBody.restitution = 1
physicsBody.friction = 0
physicsBody.linearDamping = 0
physicsBody.collisionBitMask = PhysicsCategory.Boundary
physicsBody.collisionBitMask = PhysicsCategory.Boundary | PhysicsCategory.Wall | PhysicsCategory.Water
//physicsBody.dynamic=false
// 4
self.physicsBody = physicsBody
sprite.facingBackAnim = AnimatedSprite.createAnimWithPrifix("player",suffix: "ft")
sprite.facingForwardAnim = AnimatedSprite.createAnimWithPrifix("player",suffix: "bk")
sprite.facingSideAnim = AnimatedSprite.createAnimWithPrifix("player",suffix: "lt")
sprite.runAction(sprite.facingBackAnim)
}
func moveToward(target: CGPoint) {
// _Lastlocation
let targetVector = (target - position).normalized() * 150.0
physicsBody?.velocity = CGVector(point: targetVector)
faceCurrentDirection()
}

Related

Gameover on any collision - Swift Spritekit

In my game I have planes moving around. In my game, I want so that if any plane collides with another, it prints "game over". I have added SKPhysicsContactDelegate to my gamescene. I added a physics bodies to my planes. Then, I added this function to my didMoveToView function:
func didBegin(_ contact: SKPhysicsContact){
print("Game over")
}
Now, when I run my game, and the planes collide, nothing prints to the console. How can I change my code so if any plane collides with another (there are more than 2) it prints game over to the console?
Edit: I have set the physics world contact delegate to self. I have not called this function - do I have to - I thought that this function runs when there is a collision in the scene.
Here is my code:
//
// GameScene.swift
// PlaneGame
//
// Created by Lucas Farleigh on 09/04/2017.
// Copyright © 2017 Farleigh Tech. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
private let Background = SKSpriteNode(imageNamed: "Background")
private let PlaneRed = SKSpriteNode(imageNamed: "PlaneRed")
private let PlaneBlue = SKSpriteNode(imageNamed: "PlaneBlue")
private let PlaneRed2 = SKSpriteNode(imageNamed: "PlaneRed2")
private let PlaneBlue2 = SKSpriteNode(imageNamed: "PlaneBlue2")
private let StartButton = SKLabelNode(fontNamed: "Chalkduster")
private let Trail = SKSpriteNode(imageNamed: "BlueTrail")
private let Center = SKNode()
private let Center2 = SKNode()
var GameHasStarted = false
override func didMove(to view: SKView) {
//Defining the position,size and ZPosition for the background
Background.position = CGPoint(x:self.frame.midX / 2,y: self.frame.midY)
Background.xScale = 10.0
Background.yScale = 10.0
Background.zPosition = -10
addChild(Background)
//Defining a start button - will be used later as a button
StartButton.position = CGPoint(x:self.frame.midX,y:self.frame.minY + 100)
StartButton.text = "Tap Anywhere To Start"
StartButton.fontSize = 50.0
StartButton.name = "StartButton"
addChild(StartButton)
//Setting the planered position and size up for the plane, ready to start the game
PlaneRed.position = CGPoint(x:self.frame.midX - 250,y: self.frame.midY)
PlaneRed.xScale = 0.13
PlaneRed.yScale = 0.13
PlaneRed.zPosition = 10
//Setting the planeblue position and size up for the plane, ready to start the game
PlaneBlue.position = CGPoint(x:self.frame.midX + 250,y: self.frame.midY)
PlaneBlue.xScale = 0.13
PlaneBlue.yScale = -0.13
PlaneBlue.zPosition = 10
//Setting the planered position and size up for the plane, ready to start the game
PlaneRed2.position = CGPoint(x:self.frame.midX,y: self.frame.midY + 250)
PlaneRed2.xScale = -0.13
PlaneRed2.yScale = 0.13
PlaneRed2.zPosition = 10
//Setting the planeblue position and size up for the plane, ready to start the game
PlaneBlue2.position = CGPoint(x:self.frame.midX,y: self.frame.midY - 250)
PlaneBlue2.xScale = 0.13
PlaneBlue2.yScale = 0.13
PlaneBlue2.zPosition = 10
//Making the trail
Trail.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
Trail.xScale = 1.08
Trail.yScale = 1.08
addChild(Trail)
//In order to rotate the planes around a point, we must create the point as an SKNode, and make the planes a child of the point
//The point then rotates bringing the planes with it
//Setting up the point where the plane will rotate around
Center.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
addChild(Center)
Center2.position = CGPoint(x:self.frame.midX,y:self.frame.midY)
addChild(Center2)
Center.addChild(PlaneRed)
Center.addChild(PlaneBlue)
Center2.addChild(PlaneRed2)
Center2.addChild(PlaneBlue2)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ADDING PHYSICS TO PLANES
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Defining the red planes physics body
PlaneRed.physicsBody = SKPhysicsBody(rectangleOf: PlaneRed.size)
PlaneRed2.physicsBody = SKPhysicsBody(rectangleOf: PlaneRed2.size)
physicsWorld.contactDelegate = self
physicsWorld.gravity = CGVector.zero
func didBegin(contact: SKPhysicsContact){
print("Game over")
}
}
func Start(){
//Defining an SKAction for the plane to orbit the center
let OrbitCenter = SKAction.rotate(byAngle: CGFloat(-2), duration: 3.8)
let Orbit = SKAction.repeatForever(OrbitCenter)
//Creating the action for the center 2 to rotate anti clockwise
let AntiOrbitCenter = SKAction.rotate(byAngle: CGFloat(2), duration: 3.8)
let AntiOrbit = SKAction.repeatForever(AntiOrbitCenter)
//Running the SKAction on the plane
Center.run(Orbit)
Center2.run(AntiOrbit)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
for touch in touches{
//Setting up the touch settings - these two variables store the nodes that the user has touched by first defining the location and then checking for nodes at this location
let location = touch.location(in: self)
let node = self.atPoint(location)
if GameHasStarted == false{
Start()
GameHasStarted = true
}
}
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
First
Your didBegin func needs to be outside of didMove func
override func didMove(to view: SKView) {
}
func didBegin(_ contact: SKPhysicsContact) {
print("Game over")
}
second
you need to setup some physics categories for your objects so they
know what they can collide with, what they can pass through and what
collisions don't matter. You can put this outside your class
declaration
//Game Physics
struct PhysicsCategory {
static let plane: UInt32 = 0x1 << 0
static let plane2: UInt32 = 0x1 << 1
static let obstacle: UInt32 = 0x1 << 2
}
third
You need to add those physics decorations to your objects
//Defining the red planes physics body
PlaneRed.physicsBody = SKPhysicsBody(rectangleOf: PlaneRed.size)
PlaneRed.physicsBody?.categoryBitMask = PhysicsCategory.plane
PlaneRed.physicsBody?.collisionBitMask = PhysicsCategory.plane
PlaneRed.physicsBody?.contactTestBitMask = PhysicsCategory.plane
PlaneRed.physicsBody?.isDynamic = true
PlaneRed2.physicsBody = SKPhysicsBody(rectangleOf: PlaneRed2.size)
PlaneRed2.physicsBody?.categoryBitMask = PhysicsCategory.plane
PlaneRed2.physicsBody?.collisionBitMask = PhysicsCategory.plane
PlaneRed2.physicsBody?.contactTestBitMask = PhysicsCategory.plane
PlaneRed2.physicsBody?.isDynamic = true
PlaneBlue.physicsBody = SKPhysicsBody(rectangleOf: PlaneBlue.size)
PlaneBlue.physicsBody?.categoryBitMask = PhysicsCategory.plane
PlaneBlue.physicsBody?.collisionBitMask = PhysicsCategory.plane
PlaneBlue.physicsBody?.contactTestBitMask = PhysicsCategory.plane
PlaneBlue.physicsBody?.isDynamic = true
PlaneBlue2.physicsBody = SKPhysicsBody(rectangleOf: PlaneBlue2.size)
PlaneBlue2.physicsBody?.categoryBitMask = PhysicsCategory.plane
PlaneBlue2.physicsBody?.collisionBitMask = PhysicsCategory.plane
PlaneBlue2.physicsBody?.contactTestBitMask = PhysicsCategory.plane
PlaneBlue2.physicsBody?.isDynamic = true
self.physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVector.zero

Swinging Beam that Doesn't Stop Swinging in Swift SpriteKit

I have a ios 9 spritekit game. I am adding a i-beam or a wrecking ball that should swing from a jointed rope like a pendulum. My game requires gravity and I want the beam to react to gravity and sprites that jump on the beam or hit the beam from below. When I use the following code, the beam eventually slows down and comes to rest without any interaction with other sprites. The top node in the jointed node is fixed (i.e., modeling attachment to a crane or building) I start the beam swinging by applying an impulse on the bottom node in the jointed node. I have set the friction, linear dampening, and angular dampening to 0.
What I need the beam to do prior to interacting with any sprites is to swing back and forth where the maximum height on the left swing and right swing is nearly the same throughout time. I want the beam or wrecking ball to act like its swinging from a frictionless pivot. The beam or ball doesn't go in a full circle, so I cannot use a constant angular velocity.
I tried something similar to:
Constant speed orbit around point with SKNode but neither the linear nor angular velocity is constant after the initial impulse as the beam or ball will arc up, slow down, stop at the top of the arc, and then circle back in the other direction.
let (actionSceneObjectNode, jointArray) = ActionSceneObject.createActionJointedSceneObjectAtPosition(CGPoint(x: positionX, y: positionY), ofType: actionSceneObject.type!, withImage: actionSceneObject.imageName, withActionDirection: actionSceneObject.imageDirection)
foregroundNode.addChild(actionSceneObjectNode)
if let bottomNode = actionSceneObjectNode.childNodeWithName("bottomObject") {
bottomNode.physicsBody?.applyImpulse(CGVector(dx: 50000.0, dy: 0))
}
// add the joints
for joint in jointArray {
self.physicsWorld.addJoint(joint)
}
Function
class func createActionJointedSceneObjectAtPosition(position: CGPoint, ofType type: ActionSceneObjectType, withImage imageName: String, withActionDirection actionDirection: DirectionValue) -> (ActionSceneObjectNode, [SKPhysicsJoint]) {
let node = ActionSceneObjectNode()
node.position = position
node.name = SceneObjectType.Action.rawValue
node.actionType = type
node.actionDirection = actionDirection
var jointArray = [SKPhysicsJoint]()
var sprite: SKSpriteNode
////////
// adapted from https://stackoverflow.com/questions/20811931/how-to-create-a-rope-in-spritekit
let countJointElements:Int = 3
let texture = SKTexture(imageNamed: "Rope.png")
//let textureSize = CGSize(width: texture.size().width*SceneObjectSizeScale.ActionSceneObject, height: texture.size().height*SceneObjectSizeScale.ActionSceneObject)
let topAnchor = SKSpriteNode(texture: texture, size: texture.size())
topAnchor.name = "topAnchor"
//topAnchor.position = CGPointMake(position.x, position.y) // the node holds the joint start position
topAnchor.physicsBody = SKPhysicsBody(rectangleOfSize: texture.size())
topAnchor.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.None
topAnchor.physicsBody?.affectedByGravity = false
topAnchor.physicsBody?.friction = 0.0
topAnchor.physicsBody?.restitution = 1.0
topAnchor.physicsBody?.linearDamping = 0.0
topAnchor.physicsBody?.angularDamping = 0.0
topAnchor.physicsBody?.mass = 10.0
node.addChild(topAnchor)
// by default, the joints build top to bottom
for index in 0 ..< countJointElements {
let item = SKSpriteNode(texture: texture, size: texture.size())
item.name = "ropeitem_" + String(index)
item.position = CGPointMake(0, 0 - CGFloat(index+1) * item.size.height)
item.physicsBody = SKPhysicsBody(rectangleOfSize: texture.size())
item.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.None
item.physicsBody?.affectedByGravity = true
item.physicsBody?.friction = 0.0
item.physicsBody?.restitution = 1.0
item.physicsBody?.linearDamping = 0.0
item.physicsBody?.angularDamping = 0.0
item.physicsBody?.mass = 10.0
node.addChild(item)
var bodyA = SKPhysicsBody()
if (index == 0)
{
bodyA = topAnchor.physicsBody!;
}
else
{
let nameString = "ropeitem_" + String(index - 1)
let nodeItem = node.childNodeWithName(nameString) as! SKSpriteNode
bodyA = nodeItem.physicsBody!
}
// needs to in terms of the physics world - the item position in the node is already negative
let joint = SKPhysicsJointPin.jointWithBodyA(bodyA, bodyB: item.physicsBody!, anchor: CGPointMake(position.x, position.y + item.position.y + item.size.height/2))
jointArray.append(joint)
}
let nameString = NSString(format: "ropeitem_%d", countJointElements - 1)
let lastLinkItem = node.childNodeWithName(nameString as String)
let bottomObject = SKSpriteNode(imageNamed: "I-Beam.png")
bottomObject.name = "bottomObject"
bottomObject.setScale(SceneObjectSizeScale.Platform)
bottomObject.position = CGPointMake(0, 0 + lastLinkItem!.position.y - lastLinkItem!.frame.size.height/2.0 - bottomObject.frame.size.height/2.0)
bottomObject.physicsBody = SKPhysicsBody(rectangleOfSize: bottomObject.size)
bottomObject.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.Platform
bottomObject.physicsBody?.affectedByGravity = true
bottomObject.physicsBody?.friction = 0.0
//bottomObject.physicsBody?.restitution = 1.0
bottomObject.physicsBody?.linearDamping = 0.0
bottomObject.physicsBody?.angularDamping = 0.0
bottomObject.physicsBody?.mass = 500.0
node.addChild(bottomObject)
let jointLast = SKPhysicsJointFixed.jointWithBodyA(lastLinkItem!.physicsBody!, bodyB: bottomObject.physicsBody!, anchor: CGPointMake(position.x, position.y + bottomObject.position.y + bottomObject.frame.size.height/2.0))
jointArray.append(jointLast)
///////
///////
sprite = SKSpriteNode(imageNamed: imageName)
//sprite.setScale(SceneObjectSizeScale.ActionSceneObject)
node.sprite = sprite
//node.addChild(sprite)
node.physicsBody = SKPhysicsBody(texture: texture, size: sprite.size)
node.physicsBody!.categoryBitMask = PhysicsCategoryBitmask.None
switch actionDirection {
case .Left:
node.sprite.zRotation = CGFloat(M_PI_2)
case .Right:
node.sprite.zRotation = CGFloat(-M_PI_2)
case .Down:
node.sprite.zRotation = CGFloat(M_PI)
case .Up, .Unknown:
break
}
node.physicsBody?.dynamic = true
node.physicsBody?.restitution = 0.0 // bounciness
node.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.ActionSceneObject
node.physicsBody?.collisionBitMask = 0
return (node, jointArray)
}

Stop repeatActionForever in Sprite Kit swift

I created an SKAction that repeatsForever (it's the planet spinning). But I want to stop it once the lander lands on the landing pad. So far my code is not working. I tried both removeAllActions() and removeActionForKey as you'll see. The contact detection works just fine, and there's a bunch of code not shown which includes the collision delegate, etc.
func createPlanet() {
var planet = SKSpriteNode()
planet.zPosition = 1
planet.name = "mars"
redPlanet = SKSpriteNode(imageNamed: "redPlanet")
redPlanet.name = "red"
redPlanet.zPosition = 2
redPlanet.physicsBody = SKPhysicsBody(texture: redPlanet.texture!, size: size)
redPlanet.physicsBody!.dynamic = false
redPlanet.physicsBody!.categoryBitMask = planetMask
redPlanet.physicsBody!.contactTestBitMask = 0
planet.addChild(redPlanet)
landingPad = SKSpriteNode(imageNamed: "landingPad")
landingPad.name = "pad"
landingPad.zPosition = 3
landingPad.position = CGPoint(x: 0, y: redPlanet.size.height / 2 - 60)
landingPad.physicsBody = SKPhysicsBody(rectangleOfSize: landingPad.size)
landingPad.physicsBody!.dynamic = false
landingPad.physicsBody!.categoryBitMask = landingPadMask
landingPad.physicsBody!.collisionBitMask = landerMask
landingPad.physicsBody!.contactTestBitMask = landerMask
planet.addChild(landingPad)
planet.position = CGPoint(x: frame.size.width / 2, y: -redPlanet.size.height / 6)
let spinner = SKAction.rotateByAngle(CGFloat(M_PI), duration: 3)
planet.runAction(SKAction.repeatActionForever(spinner), withKey: "planetSpin")
addChild(planet)
}
And this...
func didBeginContact(contact: SKPhysicsContact) {
if !hasLanded {
if contact.bodyA.node!.name == "lander" {
hasLanded = true
print("bodyA contact")
physicsWorld.speed = 0
removeAllActions()
removeActionForKey("planetSpin")
} else if contact.bodyB.node!.name == "lander" {
print("bodyB contact")
hasLanded = true
physicsWorld.speed = 0
removeAllActions()
removeActionForKey("planetSpin")
}
}
}
You're not removing actions from the planet node, you're removing them from the scene or parent node or whatever your didBeginContact is a member of.
Make planet a class variable and in didBeginContact, call planet.removeAllActions()

Randomize image in array in sprite kit swift.

I was wondering if someone could show me how to make it so that I can spawn random image missiles. Right now I am using one image called "meteor", I have a few more images I would like to show and randomize. I know I need to put them in an array and create an arc for random. I have done it for sound but I'm not sure how to do it for images. This is my code so far.
var lastMissileAdded : NSTimeInterval = 0.0
let missileVelocity : CGFloat = 4.0
func addMissile() {
// Initializing missile node
var missile = SKSpriteNode(imageNamed: "meteor")
missile.setScale(0.44)
// Adding SpriteKit physics body for collision detection
missile.physicsBody = SKPhysicsBody(rectangleOfSize: missile.size)
missile.physicsBody?.categoryBitMask = UInt32(obstacleCategory)
missile.physicsBody?.dynamic = true
missile.physicsBody?.contactTestBitMask = UInt32(shipCategory)
missile.physicsBody?.collisionBitMask = 0
missile.physicsBody?.usesPreciseCollisionDetection = true
missile.name = "missile"
// Selecting random y position for missile
var random : CGFloat = CGFloat(arc4random_uniform(300))
missile.position = CGPointMake(self.frame.size.width + 20, random - 20)
self.addChild(missile)
}
func moveObstacle() {
self.enumerateChildNodesWithName("missile", usingBlock: { (node, stop) -> Void in
if let obstacle = node as? SKSpriteNode {
obstacle.position = CGPoint(x: obstacle.position.x - self.missileVelocity, y: obstacle.position.y)
if obstacle.position.x < 0 {
obstacle.removeFromParent()
}
}
})
}
All you need to do is name them meteor0, meteor1 and meteor2 and use String Interpolation to create your node with your random image:
var missile = SKSpriteNode(imageNamed: "meteor\(arc4random_uniform(3))")

SpriteKit frame incorrect

I'm creating a simple game. I'm trying to set the frame as an physicsBody so the plane, never falls below the screen. The function below stops it from falling all the way off, but the SKSpriteNode falls just out of view before stopping.
func setBoundry(view: SKView) {
// Create ground
var boundry = SKNode()
boundry.physicsBody = SKPhysicsBody(edgeLoopFromRect: view.frame)
boundry.physicsBody?.dynamic = false
boundry.physicsBody?.contactTestBitMask = PhysicsCategory.Plane
boundry.physicsBody?.categoryBitMask = PhysicsCategory.Boundry | PhysicsCategory.Collidable
self.addChild(boundry)
}
Plane is being created like this...
func createPlane(sceneView: SKView) {
let planeTexture = SKTexture(imageNamed: "planeRed1")
let planeTexture1 = SKTexture(imageNamed: "planeRed2")
let planeTexture2 = SKTexture(imageNamed: "planeRed3")
// Animate plans propeller
let animation = SKAction.animateWithTextures([planeTexture, planeTexture1, planeTexture2], timePerFrame: 0.05)
let makePropellerSpin = SKAction.repeatActionForever(animation)
// Set planes position
plane = SKSpriteNode(texture: planeTexture)
plane.position = CGPointMake(size.width/4, size.height/2)
plane.runAction(makePropellerSpin)
plane.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(plane.size.width, plane.size.height))
plane.physicsBody?.dynamic = true
plane.physicsBody?.allowsRotation = false
plane.physicsBody?.categoryBitMask = PhysicsCategory.Plane
plane.physicsBody?.collisionBitMask = PhysicsCategory.Collidable | PhysicsCategory.Boundry
plane.physicsBody?.contactTestBitMask = PhysicsCategory.Collidable | PhysicsCategory.Boundry
// Set elevation
plane.zPosition = 5
self.addChild(plane)
}
You need to set the contactTestBitMask for your boundry node and also set the physics for your plane-node:
boundry.physicsBody?.contactTestBitMask = PhysicsCategory.YourPlayerEnum
Also check out the collisionBitMask property of the physicsbody.