0
votes

I have randomly spawned SKSpriteNodes left and right off the screen. They should just run through the screen and then the node gets deleted. They do what I want but I just have straight movement, I want to have them to move in an angle (later on randomly created)

This is what I have

// these lines are just to create the SpriteNode and place it off the screen

let randomObj = SKSpriteNode(imageNamed: "randomObj")

let leftOrRight:CGFloat = arc4random_uniform(2) == 0 ? 1 : -1

randomObj.position = CGPoint(x: CGFloat(leftOrRight)*(self.frame.width 
+ randomObj.frame.width), y: random(min:0 , max: self.frame.height))
    self.addChild(randomObj)

// here is the movement -> walk over the screen and delete

let distance = CGFloat(self.frame.width*2)
let moveRandomObj = SKAction.moveBy(x: (-leftOrRight)*distance + 100, 
y: 0, duration: TimeInterval(0.008 * distance))
let removeRandomObj = SKAction.removeFromParent()
let moveAndRemove = SKAction.sequence([moveRandomObj, removeRandomObj])
randomObj.run(moveAndRemove)

I tried to give it a rotation with SKAction rotate by, but then just the sprite is rotated and it still moves horizontally

Appreciate any help

1

1 Answers

1
votes

You simply need to add a random element to the y: value of :

let moveRandomObj = SKAction.moveBy(x: (-leftOrRight)*distance + 100, 
y: 0, duration: TimeInterval(0.008 * distance))

This is a MoveBy and you've told it to move by 0 points vertically, so naturally it'll move straight across. The rotation of the node has no bearing on the direction it moves in.