SKSpritenode not showing in simlulator or phone when I build app - swift

SKspritenode not showing when I build the app in simulator or phone.
I am following a youtube guide on how to create moving background in swift/xcode. My images are not showing when I build. I have tried the following:
replacing .aspectfill with .resizeFill for scaleMode
add file extension in imageNamed: "ground.png"
replacing all images with different ones.
moving the images to different folder.
class GameScene: SKScene {
var ground = SKSpriteNode()
override func didMove(to view: SKView) {
self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
}
override func update(_ currentTime: CFTimeInterval) {
}
func createGrounds() {
for i in 0...3 {
let ground = SKSpriteNode(imageNamed: "green")
ground.name = "Ground"
ground.size = CGSize(width: (self.scene?.size.width)!, height: 250 )
ground.anchorPoint = CGPoint(x: 0.5, y: 0.5)
ground.position = CGPoint(x: CGFloat(i) * ground.size.width, y: -(self.frame.size.height / 2))
self.addChild(ground)
}
func moveGround() {
self.enumerateChildNodes(withName: "Ground", using: ({
(node, error) in
node.position.x -= 2
if node.position.x < -((self.scene?.size.width)!) {
node.position.x += (self.scene?.size.width)! * 3
}
}))
}
}
}
Expecting it to create a moving background based on the images loaded.

Related

SpriteKit: How to create a region that's the same size as the device screen?

I'm working in SpriteKit and I need to create a 'playable area', an area that is same size as the device screen so that I can stop my player from moving off-screen.
I'm using the following line of code:
var playableRect: CGRect = UIScreen.main.bounds
But the resulting rectangle is about a quarter of the device screen, with a corner of that rectangle at what looks to be the center of the screen. And the device orientation doesn't change that.
I've tried everything I can think of. Nothing is working.
How do I create a rectangle that's the same size as the device screen?
Here's my full coding, after changing to include Gene's suggestion. I incorporated Gene's suggestion by revising playableRect inside the didMove method. But the result is unchanged with that coding.
import SpriteKit
import GameplayKit
import CoreMotion
#objcMembers
class GameSceneUsingTilt: SKScene {
let player = SKSpriteNode(imageNamed: "player-motorbike")
let motionManager = CMMotionManager()
var playableRect = UIScreen.main.bounds
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "road")
background.zPosition = -1
addChild(background)
if let particles = SKEmitterNode(fileNamed: "Mud") {
let farRightPt = frame.maxX // start the emitter at the far right x-point of the view
particles.advanceSimulationTime(10)
particles.position.x = farRightPt
addChild(particles)
}
let nearLeftPt = frame.minX * 3 / 4 // start the player at a quarter of the way to the far left x-point of the view
player.position.x = nearLeftPt
player.zPosition = 1
addChild(player)
motionManager.startAccelerometerUpdates()
// coding below shows outline of playableRect
let bounds = UIScreen.main.bounds
let scale = UIScreen.main.scale
// let size = CGSize(width: bounds.size.width * scale, height: bounds.size.height * scale)
playableRect = CGRect(x: 0, y: 0, width: bounds.size.width * scale, height: bounds.size.height * scale)
drawPlayableRect(rect: playableRect)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
func boundsCheck() {
let playableRect = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height)
let bottomLeft = CGPoint(x: playableRect.minX, y: playableRect.minY)
let topRight = CGPoint(x: playableRect.maxX, y: playableRect.maxY)
if player.position.x <= bottomLeft.x {
player.position.x = bottomLeft.x
}
if player.position.x >= topRight.x {
player.position.x = topRight.x
}
if player.position.y <= bottomLeft.y {
player.position.y = bottomLeft.y
}
if player.position.y >= topRight.y {
player.position.y = topRight.y
}
}
override func update(_ currentTime: TimeInterval) {
if let accelerometerData = motionManager.accelerometerData {
// note that since the game will be running in landscape mode, up and down movement is controlled by the x axis and right to left movement is controlled by the y-axis...so this is the inverse of what you'd normally think.
let changeX = CGFloat(accelerometerData.acceleration.y) * 4
let changeY = CGFloat(accelerometerData.acceleration.x) * 4
// you have to subtract from x position and add to the y position because device is rotated so the axises aren't what you would normally expect.
player.position.x -= changeX
player.position.y += changeY
// check to make sure position isn't outside payable area:
boundsCheck()
}
}
// function below shows outline of playableRect
func drawPlayableRect(rect: CGRect) {
let shape = SKShapeNode()
let path = CGMutablePath()
path.addRect(rect)
shape.path = path
shape.strokeColor = .red
shape.lineWidth = 4.0
addChild(shape)
}
}
Use: UIScreen.main.nativeBounds

Display upperLimit SKRange

So here is my code:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var ship1 = [2,1]
var ship2 = [1,2]
let jonahSpriteNode = SKSpriteNode(imageNamed: "jonah_spaceship")
let georgeSpriteNode = SKSpriteNode(imageNamed: "george_spaceship")
override func didMove(to view: SKView) {
//var jonahFrames = [SKTexture]()
jonahSpriteNode.position = CGPoint(x: 30, y: frame.midY)
jonahSpriteNode.size = CGSize(width: 100.0, height: 100.0)
addChild(jonahSpriteNode)
georgeSpriteNode.position = CGPoint(x: 628, y: frame.midY)
georgeSpriteNode.size = CGSize(width: 100.0, height: 100.0)
addChild(georgeSpriteNode)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
var touchLocation = touch.location(in: self)
var angle1 = atan2(jonahSpriteNode.position.y - touchLocation.y , jonahSpriteNode.position.x - touchLocation.x)
var angle = angle1 - CGFloat(Double.pi / 1)
makeCircularRange(to: jonahSpriteNode)
let rotate = SKAction.rotate(toAngle: angle, duration: 1.0)
let move = SKAction.move(to: CGPoint(x: touchLocation.x, y: touchLocation.y), duration: 2.5)
let sequence = SKAction.sequence([rotate, move])
jonahSpriteNode.run(sequence)
}
}
func makeCircularRange(to node: SKNode) {
let range = SKRange(lowerLimit: 0, upperLimit: 400)
let constraint = SKConstraint.distance(range, to: .zero)
node.constraints = [constraint]
}
}
I wanted to display the SKRange by showing upperLimit in a certain color. I tried making nodes around the limit and then coloring the nodes but it just showed a bunch of errors. If you have any ideas please answer.
Something like this:
The sprite node will be in the center and the circle will show where it can move.
You can make a circular shape using range.upperLimit as a radius an add to scene.
func drawCircularRangeBy(range: SKRange) {
let radius = range.upperLimit
let node = SKShapeNode(circleOfRadius: radius)
node.strokeColor = .white
addChild(node)
}
Take a look of this example: https://github.com/Maetschl/SpriteKitExamples/blob/master/CircularRange/CircularRange/GameScene.swift
If you really need dots instead of a line please see this answer: Drawing dashed line in Sprite Kit using SKShapeNode

Swift - SpriteKit how do I do infinite background scrolling with two unique backgrounds?

My code works perfectly fine for one common background but I am unable to figure out the required logic have it working perfectly fine if the backgrounds were unique.
override func didMove(to view: SKView)
{
createBackground()
}
func createBackground ()
{
var texture1 = SKTexture(imageNamed: "card1")
let texture2 = SKTexture(imageNamed: "card2")
for i in 0...1
{
let background = SKSpriteNode(texture: texture1)
background.anchorPoint = CGPoint.zero
background.position = CGPoint(x: 0, y: texture1.size().height * CGFloat(i))
addChild(background)
let moveDown = SKAction.moveBy(x: 0, y: -background.size.height, duration: 5)
let reset = SKAction.moveBy(x: 0, y: background.size.height, duration: 0)
let sequence = SKAction.sequence([moveDown, reset])
let forever = SKAction.repeatForever(sequence)
background.run(forever)
texture1 = texture2
}
}
}

My SKSpriteNode wouldn't show even though I used addChild in swift

I tried to add an image to my Game Scene, but it won't appear. Below is my code. I hope you guys can help me
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var Ground = SKSpriteNode()
var iceCream = SKSpriteNode()
override func didMove(to view: SKView) {
Ground = SKSpriteNode(imageNamed: "background")
Ground.setScale(0.5)
Ground.position = CGPoint(x: self.frame.width / 2, y: self.Ground.frame.height / 2)
self.addChild(Ground)
iceCream = SKSpriteNode(imageNamed: "VanillaIceCream")
iceCream.size = CGSize(width: 60, height: 70)
iceCream.position = CGPoint(x: self.iceCream.frame.width, y: self.frame.height / 2)
self.addChild(iceCream)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: CFTimeInterval) {
}
}
When you set position tox: self.iceCream.frame.width
you position it using iceCream.
I believe that changing it to x: self.frame.width / 2 will solve it.
If it is not mistake and you want to set the iceCream on the left of the screen, position the sprite after adding it to self.
It's also good to set zPosition to each element, to make sure it will not hide behind the background image.
EDIT:
Here is the full code for your method (ready to copy/paste):
Ground = SKSpriteNode(imageNamed: "background")
self.addChild(Ground)
Ground.setScale(0.5)
Ground.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
Ground.zPosition = 1.0
iceCream = SKSpriteNode(imageNamed: "VanillaIceCream")
self.addChild(iceCream)
iceCream.size = CGSize(width: 60, height: 70)
iceCream.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
iceCream.zPosition = 2.0

Up and down movement in sprite kit and swift?

Right now, I am creating a new game that will involve a ball that moves up and down the screen by itself without touching a button or the screen. I have been looking everywhere for a solution, but I haven't found one. I know how to make the ball move up and down in objective-c, but not in swift or spritekit. I don't know if the following code will help or not. Any solution is accepted.
class GamePlayScene: SKScene, SKPhysicsContactDelegate {
var ball = SKSpriteNode(imageNamed: "green ball.png")
override func didMoveToView(view: SKView) {
//setup scene
physicsWorld.gravity = CGVector.zeroVector
self.scene?.backgroundColor = UIColor.blackColor()
self.scene?.size = CGSize(width: 640, height: 1136)
ball.position = CGPoint (x: self.size.width * 0.5, y: self.size.width * 0.9)
ball.size = CGSize (width: 80, height: 82)
let moveBallUp = SKAction.moveToY(600, duration: 0.4)
let moveBallDown = SKAction.moveToY(293, duration: 0.4)
self.addChild(ball)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
let moveBallUp = SKAction.moveToY(600, duration: 0.4)
let moveBallDown = SKAction.moveToY(293, duration: 0.4)
if ball.position.y == 600 {
self.ball.runAction(moveBallUp)
} else {
self.ball.runAction(moveBallDown)
}
}
}
I suggest you use repeatActionForever. If you start your ball position from the bottom of the screen this sequence should work. If you want to start the ball from the top then switch the positions of the actions in moveUpAndDown with each other.
func moveSprite() {
let moveBallUp = SKAction.moveToY(600, duration: 0.4)
let moveBallDown = SKAction.moveToY(293, duration: 0.4)
let moveUpAndDown = SKAction.sequence([moveBallUp, moveBallDown])
let moveUpAndDownForever = SKAction.repeatActionForever(moveUpAndDown)
ball.runAction(moveUpAndDownForever)
}