1

enter image description here

Above is an image of my game. A top-down game. Wherever on the screen the player touches, I want the bullets to go to that location with a duration. I also want the player to be able to drag around his finger on the screen, and the same thing happens. So that the player doesn't have to touch the screen everytime he wants to shoot.

I've tried some different stuff so far but nothing seems to work.

First off, I dont know if I should have a separate function for the bullet. But anyway, this is my bullet function.

func spawnBullets() {
    let bullet = SKSpriteNode(imageNamed: "Bullet")
    bullet.name = "Bullet"
    bullet.zPosition = 4
    bullet.position = CGPoint(x: player.position.x + 19, y: 
    player.position.y)
    self.addChild(bullet)
}

I also have a "timer" for the bullet in the didMove function:

var timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, 
selector: Selector("spawnBullets"), userInfo: nil, repeats: true)

And lastly, this is my touchesBegan function:

override func touchesBegan(_ touches: Set<UITouch>, with event: 
UIEvent?) {        
    for  touch in touches {            
        let location = touch.location(in: self)            
        let moveToPoint = SKAction.move(to: location, duration: 0.5)
        let repeatAction = SKAction.repeatForever(moveToPoint)            
        bullet.run(moveToPoint)
    }

}
3
  • What happens when you run this code? I haven't run this code myself or analysed it too closely, but does it compile? I would think that the bullet.run in touchesBegan would fail to compile as you don't have a bullet property. I would create a bulletTarget property, use that as the 'moveTo' location, and create and apply the SKAction to move the buller within your spawnBullet method.
    – Steve Ives
    Aug 15, 2017 at 7:28
  • I don't get any errors but the bullets doesn't move. I'm sort of new to the app development, what do you mean by bulletTarget property?
    – Flinigan
    Aug 15, 2017 at 13:08
  • Where do you define the 'bullet' variable used in bullet.run(moveToPoint) in your ``touchesBegan? You must define it somewhere (with a var bullet = ...). If it's defined outside of any method (so with global scope within the class), then its referred to as a 'property. But this 'bullet' is almost certainly not the 'bullet' that you add to your scene in spawnBullets, which is why they don't move. I'll try to post an answer based on your code later.
    – Steve Ives
    Aug 15, 2017 at 13:21

1 Answer 1

2

Here you go - a simple app with a ship you can drag around the screen and missiles that shoot towards the location of a touch.

If you touch the ship you can drag it around; touch outside the ship and a missile will shoot from the ship to the touch location.

import SpriteKit

class GameScene: SKScene {

var ship = SKSpriteNode()
var shipIsTouched = false
var missileDestination = CGPoint()
let missileSpeed: CGFloat = 800 // Points per second)
let missileFireRate : TimeInterval = 0.2 // Seconds between each missile

override func didMove(to view: SKView) {
    missileDestination = CGPoint(x: 0, y: (self.size.height / 2))
    createPlayerShip()
    let fire = SKAction.sequence([SKAction.run(fireMissile), SKAction.wait(forDuration: missileFireRate)])
    run(SKAction.repeatForever(fire))
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        if ship.contains(touch.location(in: self)) {
            shipIsTouched = true
        } else {
            missileDestination = touch.location(in: self)
            ship.zRotation = direction(to: missileDestination, from: ship.position) - CGFloat(Double.pi/2)
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if (shipIsTouched == true) {
        ship.position = (touches.first?.location(in: self))!
        ship.zRotation = direction(to: missileDestination, from: ship.position) - CGFloat(Double.pi/2)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if shipIsTouched {
        shipIsTouched = false
    }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}

func createPlayerShip() {
    ship = SKSpriteNode(imageNamed: "Spaceship")
    ship.zRotation = CGFloat(-Double.pi/2.0)
    ship.scale(to: CGSize(width: 150, height: 150))
    ship.position = CGPoint(x: -size.width/2 + 200, y: 0)

    addChild(ship)
}


func fireMissile() {
    let missile = SKSpriteNode(color: .white, size: CGSize(width: 50, height: 10))
    missile.position = ship.position

    let missileFlightTime = travelTime(to: missileDestination, from: ship.position, atSpeed: missileSpeed)
    missile.zRotation = direction(to: missileDestination, from: missile.position)

    addChild(missile)

    let missileMove = SKAction.move(to: missileDestination,
                                    duration: TimeInterval(missileFlightTime))
    let missileRemove = SKAction.removeFromParent()
    missile.run(SKAction.sequence([missileMove, missileRemove]))
}

func travelTime(to target : CGPoint, from : CGPoint, atSpeed speed : CGFloat) -> TimeInterval {
    let distance = sqrt(pow(abs(target.x - from.x),2) +
        pow(abs(target.y - from.y),2))
    return TimeInterval(distance/speed)
}


func direction(to target : CGPoint, from: CGPoint) -> CGFloat {
    let x = target.x - from.x
    let y = target.y - from.y
    var angle = atan(y / x)
    if x < 0 {
        angle = angle + CGFloat.pi
    }
    return angle
}
}

There's a bit of extra trickery to make the missiles speed consistent (since moveTo takes a time, not a speed, so if the destination was close the missiles would move slowly, and if further away they'd move faster) and to make the missiles rotate to face the destination.

You could create a curved path for the missiles to follow to the destination, which would look cool but may not be appropriate for your app.

EDIT:

If you want the ship stationary, and the missiles to follow your finger, replace all the code down to createPlayerShip with this (yes, we've lost touchesEnded() and update():

import SpriteKit

class GameScene: SKScene {

var ship = SKSpriteNode()
var missileDestination = CGPoint()
let missileSpeed: CGFloat = 800 // Points per second)
let missileFireRate : TimeInterval = 0.2 // Seconds between each missile

override func didMove(to view: SKView) {
    missileDestination = CGPoint(x: size.height/2, y: 0)
    createPlayerShip()
    let fire = SKAction.sequence([SKAction.run(fireMissile), SKAction.wait(forDuration: missileFireRate)])
    run(SKAction.repeatForever(fire))
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
            missileDestination = touch.location(in: self)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        missileDestination = (touches.first?.location(in: self))!
} 
7
  • Wow, even though I don't need all of that in THIS game, all of that certainly is valuable for me in the future! Thanks! I want the player to be static, and I changed a few things from your code to make it so. One question though, how do you use the touchesMoved so that the player doesn't have to touch on the screen every time he wants to change direction of the bullets? Instead just "drag" the finger around on the screen and move the bullets to that direction?
    – Flinigan
    Aug 15, 2017 at 16:41
  • @Flinigan I think that (as you’ve removed the code to make the ship draggable) you can just set ‘missileDestination’ in touchesMoved instead of ‘ship.position’.
    – Steve Ives
    Aug 15, 2017 at 18:55
  • @Finegan See my edit for a stationary ship and missiles that 'follow' your finger... anything that doesn't make sense, please ask.
    – Steve Ives
    Aug 15, 2017 at 21:37
  • Aaah, there we go! Now it works EXACTLY as I want it to! This surely will be helpful for other people as well! :) One sidenote, do you know how to sync the starting position of the missile with the rotation of the player so that it always looks like the missiles is coming from the players gun. I've changed the "missile.position = player.position" to "missile.position = CGPoint(x: player.position.x + 25, y: player.position.y))" to adjust it more to the gun, but it still looks poorly when the player rotates, it doesn't look like it comes from the gun.
    – Flinigan
    Aug 17, 2017 at 14:44
  • @Flinigan An easy way would be to have the gun always point at your target. A more difficult (but interesting) way would be to have the missile fire forward ‘out’ of the barrel and then curve to the target. Which would you prefer? 😀
    – Steve Ives
    Aug 17, 2017 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.