Creating a background sprite node - swift

I'm trying to create an endless scroller game and I'm trying to create two backgrounds.
I have a background class like so,
class BackgroundMG1: SKNode {
let background: SKSpriteNode
let size: CGSize
init(size: CGSize) {
self.size = size
let hue = CGFloat((arc4random() % 1000) / 1000)
let randomColor = UIColor(hue: hue, saturation: 1, brightness: 1, alpha: 1)
self.background = SKSpriteNode(color: randomColor, size: size)
super.init()
setup()
}
func setup() {
background.position.x = 0
background.position.y = 0
addChild(background)
}
}
I'm going to be populating my background with other objects so I needed it to be a class and not just a static image.
I have my game scene like so,
class AntarcticaMiniGame1: SKScene {
var player: SKSpriteNode!
var backgrounds: [BackgroundMG1]!
override func didMove(to view: SKView) {
setup()
}
func setup(){
// Initializers
player = Player()
// Positions
player.position.x = 0
player.position.y = 0
player.zPosition = 1
// Set up backgrounds
backgrounds = [BackgroundMG1]()
for i in 0..<2 {
let background = BackgroundMG1(size: size)
background.position.x = CGFloat(i) * size.width
background.position.y = 0
backgrounds.append(background)
addChild(background)
}
// Add to scene
addChild(player)
}
override func update(_ currentTime: TimeInterval) {
player.physicsBody!.applyForce(CGVector(dx: 25, dy:0))
}
}
You can also assume that I have a ground and camera object set up. I had to omit that code because it's not relevant to this question. The player stays on the ground and the camera follows the player.
Right now, when I load the game, the player object is moving to the right as expected. I see one background, but the second one doesn't show up.
I feel like I'm making some mistakes with the positioning. I'm not a 100% how the coordinate system works in Swift.
Edit: My scene is connected to a .sks file which is totally empty right now. The game is in landscape orientation.

Related

How Can I increase radius of SKShapeNode by 1 pixel every second?

I am trying to write a function where I can increase SKShapeNode radius every second, but don't know how:(
var eRadius: CGFloat = 20
var eCircle = SKShapeNode()
override func didMove(to view: SKView) {
super.didMove(to: view)
eCircle = SKShapeNode(circleOfRadius: eRadius)
eCircle.strokeColor = .black
eCircle.glowWidth = 1.0
eCircle.fillColor = .white
eCircle.fillTexture = SKTexture(imageNamed: "e")
addChild(eCircle)
gameTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(addRadius), userInfo: nil, repeats: true)
}
#objc func addRadius(){
eRadius += 1
???? :(
}
Thank you!
Here's a working solution:
import SpriteKit
class GameScene: SKScene {
private var eRadius: CGFloat = 20
private var eCircle = SKShapeNode()
override func didMove(to view: SKView) {
eCircle.strokeColor = .black
eCircle.glowWidth = 1.0
eCircle.fillColor = .white
eCircle.fillTexture = SKTexture(imageNamed: "e")
addChild(eCircle)
run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
self.updateCirclePath()
self.eRadius += 1
}, SKAction.wait(forDuration: 1.0)])))
}
private func updateCirclePath() {
eCircle.path = UIBezierPath(ovalIn: CGRect(x: -eRadius * 0.5, y: -eRadius * 0.5, width: eRadius, height: eRadius)).cgPath
}
}
Basically, you create the circle using a UIBezierPath and then update it as your radius changes. For the updating you should use a forever-repeating SKAction sequence that both sets the path, then changes the radius. I chose to do the path first, then update the radius for the next upcoming turn, for clarity.
You can also do it the opposite way, so run the update function first to set the initial path, then wait one second, after which you change the radius, then update the path based on that radius.
In SpriteKit, you should use SKActions for timers instead of scheduling or dispatch queues. With SKActions, everything conforms to the same game time, which you can then control by pausing and whatever.
Also, there are multiple ways to make a circle using UIBezierPath, including ovals, rounded rectangles and arcs: https://developer.apple.com/documentation/uikit/uibezierpath.

How to add a sprite from another class on the gameScene

can anyone explain how to add a node to the gameScene please.
I subclassed my Boss class but i dont know how i can display my Boss1 on the GameScene
class Boss: GameScene {
var gameScene : GameScene!
var Boss1 = SKSpriteNode(imageNamed: "boss1")
override func didMove(to view: SKView) {
Boss1.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
Boss1.zPosition = 2
self.gameScene.addChild(Boss1)
}
}
im using swift 4 and xcode 9
You don't generally subclass the scene for instances such as this. More likely you are meaning to make boss a subclass of SKSpriteNode and adding it to your scene. While there is probably dozens of ways that you could subclass this, this is just 1 way.
Also worth noting that it is not generally acceptable practice to make your variable names capitalized, classes yes, variables no.
class Boss: SKSpriteNode {
init() {
let texture = SKTetxure(imageNamed: "boss1")
super.init(texture: texture , color: .clear, size: texture.size())
zPosition = 2
//any other setup such as zRotation coloring, additional layers, health etc.
}
}
...meanwhile back in GameScene
class GameScene: SKScene {
let boss1: Boss!
override func didMove(to view: SKView) {
boss1 = Boss()
boss1.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
self.gameScene.addChild(boss1)
}
}
in GameScene you create an instance of the new class and position it and add it in the GameScene.
edit
the init function has a short cut in swift.
Boss()
is the same as
Boss.init()
you can also add custom parameters to your init in order to further clarify or add more features to your class. for example...
class Boss: SKSpriteNode {
private var health: Int = 0
init(type: Int, health: Int, scale: CGFloat) {
let texture: SKTetxure!
if type == 1 {
texture = SKTetxure(imageNamed: "boss1")
}
else {
texture = SKTetxure(imageNamed: "boss2")
}
super.init(texture: texture , color: .clear, size: texture.size())
self.health = health
self.setScale(scale)
zPosition = 2
//any other setup such as zRotation coloring, additional layers, health etc.
}
}

Get SKCameraNode to follow a hero Spritenode

I can't seem to figure this out. I've tried many different things and none of them seem to work. With my current code, the camera and the hero never line up and the scene seems to jump pretty far when I touch the screen. All I want to do is when I touch the screen have the hero move to the touch point and have the camera follow him. Is there some way to lock the camera to the hero spritenode?
import SpriteKit
let tileMap = JSTileMap(named: "level2.tmx")
let hero = SKSpriteNode(imageNamed: "hero")
let theCamera: SKCameraNode = SKCameraNode()
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.anchorPoint = CGPoint(x: 0, y: 0)
self.position = CGPoint(x: 0, y: 0)
hero.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
hero.xScale = 0.5
hero.yScale = 0.5
hero.zPosition = 2
tileMap.zPosition = 1
tileMap.position = CGPoint(x: 0, y: 0)
self.addChild(tileMap)
self.addChild(hero)
self.addChild(theCamera)
self.camera = theCamera
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let action = SKAction.moveTo(location, duration: 1)
hero.runAction(action)
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
self.camera?.position = hero.position
}
}
The reason why you saw the scene jumped pretty far is because the scene.size doesn't equal to the screen size. I guess you might initialize your first scene like this:
// GameViewController.swift
if let scene = GameScene(fileNamed:"GameScene") {...}
That code will load GameScene.sks whose size is 1024*768 by default. But since you add your SKSpriteNode programmatically, you can initialize the scene in this way to fit the screen size:
// GameViewController.swift
// Only remove if statement and modify
let scene = GameScene(size: view.bounds.size) ...
This will solve most of the problem you have. Moreover, I suggest moving the camera node using SKAction:
override func update(currentTime: CFTimeInterval) {
let action = SKAction.moveTo(hero.position, duration: 0.25)
theCamera.runAction(action)
}
The last thing, add this line to align the camera with your hero at the start:
self.camera?.position = hero.position

How to detect collision without physics

I want to detect when two bodies contact without using didBeginContact() function
I try with CGRectIntersectsRect() without any effect.
class GameScene: SKScene, SKPhysicsContactDelegate {
// Player
var _player = SKNode()
var platform = SKNode()
let heroCategory: UInt32 = 1 << 0
let platformCategory: UInt32 = 1 << 1
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// Setup
self.anchorPoint = CGPointMake(0.5, 0.5)
self.physicsWorld.gravity = CGVectorMake(0.0, -2.0);
self.physicsWorld.contactDelegate = self
// Start populating
_player = creatPlayer()
self.addChild(_player)
platform = creatPlatform(1, atPosition: CGPoint(x: 0, y: -200))
self.addChild(platform)
let platformTwo = creatPlatform(2, atPosition: CGPoint(x: 0, y: 200))
self.addChild(platformTwo)
}
func creatPlatform(type: Int, atPosition: CGPoint) -> PlatformNode {
let node = PlatformNode()
node.platformType = type
node.position = atPosition
let sprite = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 200, height: 50))
node.addChild(sprite)
node.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
node.physicsBody?.dynamic = false;
node.physicsBody?.categoryBitMask = platformCategory
node.physicsBody?.contactTestBitMask = heroCategory
node.physicsBody?.collisionBitMask = 0;
return node
}
func creatPlayer() -> SKNode {
let playerNode = SKNode()
let sprite = SKSpriteNode(color: UIColor.whiteColor(), size: CGSize(width: 50, height: 50))
playerNode.addChild(sprite)
playerNode.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
playerNode.physicsBody?.dynamic = false
playerNode.physicsBody?.allowsRotation = false
playerNode.physicsBody?.restitution = 1.0
playerNode.physicsBody?.friction = 0.0
playerNode.physicsBody?.angularDamping = 0.0
playerNode.physicsBody?.linearDamping = 0.0
playerNode.physicsBody?.categoryBitMask = heroCategory
playerNode.physicsBody?.contactTestBitMask = platformCategory
playerNode.physicsBody?.collisionBitMask = 0;
return playerNode
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
_player.physicsBody?.dynamic = true
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if(CGRectIntersectsRect(platform.frame, _player.frame)){
println("Collision")
}
}
}
Maybe using CGRectIntersectsRect is a wrong approach, but I can be used instead?
The frame property
The frame property is a rectangle in the parent’s coordinate system
that contains the node’s content, ignoring the node’s children.
Also from docs:
The frame is non-empty if the node’s class draws content.
And because SKNode class does not perform any drawing of its own, and your platform is probably subclass of SKNode and player is SKNode the frame property is always (0,0,0,0).
You can access the real size of a frame in few ways:
You can make player and platform as subclasses of SKSpriteNode.
You can leave them as they are and access the child SKSpriteNode inside them.
You can leave as they are and use calcualteAccumulatedFrame() method.
About calcualteAccumulatedFrame() from docs:
A node’s accumulated frame, retrieved by calling the
calculateAccumulatedFrame method, is the largest rectangle that
includes the frame of the node and the frames of all its descendants.

Attemped to add a SKNode which already has a parent - Swift

Ok. this code is driving me crazy. It just don't work. The only message I received is "Attemped to add a SKNode which already has a parent". Yes I know that there has been some discussions here, but none of them give the solution I need.
This is the code. I really appreciate any help.
import SpriteKit
class MyScene: SKScene {
let intervalShapeCreation:NSTimeInterval = 2.0 // Interval for creating the next Shape
let gravitationalAcceleration:CGFloat = -0.5 // The gravitational Y acceleration
let shapeSequenceAction = SKAction.sequence([
SKAction.scaleTo(1.0, duration: 0.5),
SKAction.waitForDuration(2.0),
SKAction.scaleTo(0, duration: 0.5),
SKAction.removeFromParent()
])
override init(size: CGSize) {
super.init(size: size)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
addBackground()
initializeScene()
}
// MARK: Level Building
func initializeScene() {
self.physicsWorld.gravity = CGVectorMake(0.0, gravitationalAcceleration)
runAction(SKAction.repeatActionForever(
SKAction.sequence([SKAction.runBlock(self.createShape),
SKAction.waitForDuration(intervalShapeCreation)])))
}
func addBackground() {
let backgroundAtlas = SKTextureAtlas(named: "background")
let background = SKSpriteNode(texture: backgroundAtlas.textureNamed("background"))
background.position = CGPoint(x: size.width/2, y: size.height/2)
background.anchorPoint = CGPointMake(0.5, 0.5)
background.zPosition = -1
background.name = "background"
self.addChild(background)
}
func createShape() {
let newShape = sSharedAllPossibleShapes[0]
print("\n shape creada: \(newShape.name)")
newShape.position = CGPointMake(size.width / 2, CGFloat( Int.random(fromZeroToMax: 500)))
self.addChild(newShape)
newShape.runAction(shapeSequenceAction)
}
}
createShape doesn't actually create a SKShapeNode. It gets the first shape from the sSharedAllPossibleShapes array, then adds it as child to self. The second time you call this method that shape already has a parent and can't be added again.
You have to create a new instance of SKShapeNode. The way I see it your array here really needs to contain the CGPath objects that define the shape, not the nodes themselves because you can't reuse nodes the way you intended to.