1

I've searched and I can only find things about making it move by swipping/dragging. I'm a beginner making a game on Xcode with Sprite-Kit, and I'm doing pretty well so far, better than expected to be honest.

But I cant seem to figure out how to make a sprite move left and right when hitting left and right buttons. I made the left SKSpriteNode and right SKSpriteNode (I don't think that's correct) and they show up where I want obviously, but I don't know how to enable them to be touched and make the sprite move.

Sorry if this is a really amateur question, the answer will probably be obvious but I'm in a jam.

Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
TroyDeJ
  • 51
  • 5
  • The general idea of moving sprites is to affect on their position property or their velocity vectory(sprite.physicsBody.velocity). You are directly changing position property by setting it to a new value, or indirectly using SKActions like Mina pointed. When it comes to physics, you are directly changing velocity vector by setting it to a new value, and indirectly by applying impulses or forces to a physics body. Those are fundamentals to keep in mind. – Whirlwind Dec 27 '16 at 08:33

1 Answers1

3

There are a lot of tutorials about moving sprites, begin with this raywenderlich tutorial. You have to set name for your sprites and handle the movement in touchesBegan function (use this thread)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in (touches) {
        let positionInScene = touch.location(in: self)
        let touchedNode = self.atPoint(positionInScene)
        if let name = touchedNode.name {
            if name == "leftButton" {
                //move to left
            }
            if name == "rightButton" {
                //move to right
               let moveAction: SKAction = SKAction.moveBy(x: 15, y: 0, duration: 1)
               yourNode.run(moveAction)
            }
        }
    }
}
Community
  • 1
  • 1
Mina
  • 2,167
  • 2
  • 25
  • 32
  • its works until i press one the "buttons", then it instantly crashes. im not sure where the issue is for such a simple thing – TroyDeJ Dec 24 '16 at 18:37
  • 1
    Add exception break point for better information of the crash and tell us about it – Mina Dec 24 '16 at 18:50
  • ok i got it to not crash but the player still doesnt move, i didnt code a position for the player tho, its in the middle anchor point, not sure if thats any reason. – TroyDeJ Dec 24 '16 at 20:33
  • it will move to right 15 points whenever you touch the right button. if you want to just press the button once and player still moving it needs a little changes, tell me what do you exactly want? – Mina Dec 25 '16 at 05:19