Lucas Farleigh
Lucas Farleigh

Reputation: 1178

How do I make a node move in sprite kit swift

I have been wondering how to do this for a long time I am using Sprite Kit swift, my problem is that don't know how to make a node move with SKActions so basicly when the go on the scene that I put it on they see a node moving (name the node sprite) ,I do not understand how it works can someone please show me an explained example on how to do this, thank you in advance!

Upvotes: 5

Views: 5805

Answers (3)

JustAnotherGuy
JustAnotherGuy

Reputation: 259

You can give actions to a Node or Sprite in Swift 3.0... First, we will change the size of the Node, or Sprite.

let nodeSize = SKAction.scale(to: 0.5, duration: 2)

In two seconds, this will change the size of the object from whatever it is to half that size. Next, to move the Node or Sprite to a different place, use...

let nodeSet = SKAction.moveBy(x: -3.0, y: 2.0, duration: 2)

In two seconds, the object will move to the left 3 units, and up 2.

If you want to assign these actions to a specific node, you can first create a node var parentNode = SKShapeNode() and then you can tell them to run the action.

parentNode.run(nodeSize)
parentNode.run(nodeSet)

Hope that this helps.

Upvotes: 1

Petr Lazarev
Petr Lazarev

Reputation: 3182

As I understand you have a scene with some node (e.g. name="myNode").

First of all, you need to access this node:

override func didMoveToView(view: SKView) {
  let myNode = childNodeWithName(homeButtonName)!
  ...
}

Now you have a reference to your node.

Next step is to add action to move this node. For example, let's move this node +20 horizontally and -30 vertically in 3 seconds:

let dX = 20
let dY = -30
let moveAction = SKAction.moveByX(CGFloat(dX), y: CGFloat(dY), duration: 3.0)
myNode.runAction(moveAction)

You can change many node's properties, not only position, e.g. size, alpha, rotation etc.

Upvotes: 2

Entitize
Entitize

Reputation: 4969

To move a Sprite in Sprite-Kit you can use SKActions.

For example:

let action = SKAction.moveByX(3, y: 2, duration: 10)
  • This will make the sprite move 3 units along the x-axis and 2 units along the y axis in 10 seconds.

If you want your sprite to move to a specific place, you can do:

let action2 = SKAction.moveTo(location: CGPoint, duration: NSTimeInterval)

Hope this helped!

Upvotes: 5

Related Questions