Learn Courses My Dashboard

Using GameplayKit to control a D pad in the Scene

So I am working through a book by Tammy Coron "Apple Game Frameworks and Technologies. So I have built the d pad to control a character. It builds and runs fine, however when I touch the d pad arrows the character does not move.

The Player swift code:

import SpriteKit

enum Direction: String {
case stop
case left
case right
case up
case down
}

class Player: SKSpriteNode {

func move(_ direction: Direction) {
print(" Entering Switch move player: (direction.rawValue)")
switch direction {

case .up:
  print("d-up")
  self.physicsBody?.velocity = CGVector(dx: 0, dy: 100)
  // self.physicsBody?.applyImpulse(CGvector(dx; 0, dy: 100))
  //self.physicsBody?.applyForce(CGVector(dx: 0. dy; 100))
case .down:
  print("d-down")
  self.physicsBody?.velocity = CGVector(dx: 0, dy: -100)
case .left:
  print("d-left")
  self.physicsBody?.velocity = CGVector(dx: -100, dy: 0)
case .right:
  print("d-right")
  self.physicsBody?.velocity = CGVector(dx: 100, dy: 0)
case .stop:
  print("p-stop")
  stop()

}

}

func stop() {
print(“stopping player”)
self.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
}
}

This is the code from the GameScene.swift file:
func touchDown(atPoint pos : CGPoint) {
print(“inside touchDown”)
let nodeAtPoint = atPoint(pos)
if let touchedNode = nodeAtPoint as? SKSpriteNode {
if touchedNode.name?.starts(with: “controller_”) == true {
let direction = touchedNode.name?.replacingOccurrences(of: “controller_”, with: “”)
player?.move(Direction(rawValue: direction ?? “stop”)!)
}
}
}

If you could give me some hints as to what to check. I’ve been through the code multiple times and as far as I can see it should work…

Any help would be appreciated.

Thank you,

Bob

Im not sure if applying velocity is enough to make it move… You also need to move the coordinates itself (even just a little) to get it going… You know its like revving a car but it really wont move unless you change gears

Do you have an cwc+ membership? I made a simple spritekit game there maybe you can pick up something to help… Theres no D-pad though but the concept of movement should be the same

1 Like

Thank you! I am a CWC+ member and actually completed your tutorial on SpriteKit. I will revisit this today.

Thank you!!

Bob

1 Like