Flinigan
Flinigan

Reputation: 105

Moving SKSpriteNode to direction of touch

Here you have an printscreen of the game:

enter image description here

I have a static SKSpriteNode(the player) that is rotating to the direction of the touch. This is the code I have for that:

class GameplayScene: SKScene, SKPhysicsContactDelegate {

static let Pi = CGFloat(Double.pi)
static let DegreesToRadians = Pi / 180

override func touchesMoved(_ touches: Set<UITouch>, with event: 
UIEvent?) {
    let curTouch = touches.first! as UITouch
    let curPoint = curTouch.location(in: self)

    let deltaX = self.player.position.x - curPoint.x
    let deltaY = self.player.position.y - curPoint.y
    let angle = atan2(deltaY, deltaX)

    self.player.zRotation = angle + 90 * GameplayScene.DegreesToRadians
}
}

Now, I want to shoot bullets every second from the player that moves in the same direction as the touch of the screen. When the bullet moves outside of the screen, I want to implement "SKAction.removeFromParent".

Here is my fireMissile function:

func fireMissile() {
    let missile = SKSpriteNode(color: .yellow, size: CGSize(width: 20, 
    height: 5))
    missile.name = "Missile"
    missile.position = CGPoint(x: player.position.x + 30, y: 
    player.position.y)
    missile.zPosition = 2
    missile.physicsBody = SKPhysicsBody(rectangleOf: missile.size)
    missile.physicsBody?.isDynamic = false
    missile.physicsBody?.categoryBitMask = ColliderType.Bullet
    missile.physicsBody?.collisionBitMask = ColliderType.Enemy
    missile.physicsBody?.contactTestBitMask = ColliderType.Enemy

    self.addChild(missile)

}

Upvotes: 1

Views: 387

Answers (1)

Bruce
Bruce

Reputation: 361

For the timer, you'll want to use this:

run(SKAction.repeatForever(SKAction.sequence([SKAction.run {
        yourFunction()
        }, SKAction.wait(forDuration: 1)])), withKey: "key")

As for the missile shooting, add SKActions in sequential order. The first should put the bullet in front of your player, the second would move the missile, and third would delete, but this will only run after the other lines due to the sequence. Make sure you have a key to this sequence if you want to stop it later mid animation. Should look something like this:

missile.zRotation = player.zRotation
missile.position = CGPoint(x:player.size.width/2*cos(player.zRotation)+player.position.x ,y:player.size.height*sin(player.zRotation)+player.position.y)
 missile.run(SKAction.sequence([SKAction.move(to: CGPoint(x:frame.size.width*cos(player.zRotation)+player.position.x ,y:frame.size.height*sin(player.zRotation)+player.position.y), duration: 0.5), SKAction.removeFromParent()]), withKey: "move")

Upvotes: 1

Related Questions