I am brand new to XCode, SpriteKit, and Swift in general. I am trying to develop a simple mobile game where the player can shoot fireballs using the A button of the GCVirtualController. I want one fireball to shoot when the user taps the button and multiple fireballs to steadily shoot when the player holds the button.
The issue I'm having is figuring out how to distinguish a tap from a hold. Touching the button at all causes a ton of sprites to spawn instantly as if there's no way to just shoot once. Currently I am checking if the user presses the A button within the update
function since I couldn't figure out how to make it work within a touchesBegan
or touchesEnded
function.
Below is update
and the function shootFireball
which creates and moves the fireball. I know the if statement in shootFireball
is stupid, but I was messing around for a while for any way to just get one fireball to spawn and shoot at a time.
Any guidance is greatly appreciated.
override func update(_ currentTime: TimeInterval) {
// Joystick Movement //
playPosX = CGFloat((virtualController?.controller?.extendedGamepad?.leftThumbstick.xAxis.value)!)
playPosY = CGFloat((virtualController?.controller?.extendedGamepad?.leftThumbstick.yAxis.value)!)
if playPosX >= 0.5 {
player.position.x += 3
}
if playPosX <= -0.5 {
player.position.x -= 3
}
if playPosY >= 0.5 {
player.position.y += 3
}
if playPosY <= -0.5 {
player.position.y -= 3
}
// Basic Attack: A Button //
let aPress = virtualController?.controller?.extendedGamepad?.buttonA.isPressed
// Check if the A button is being pressed
if(aPress == true){
// Temporary value. Want to get the direction of fireball from the joystick's positioning
let direct = CGVectorMake(player.position.x, player.position.x)
// Call method to create and shoot fireball
let fireBullet = SKAction.run(){
self.shootFireball(direction: direct)
}
// Small delay before firing another fireball
let wait = SKAction.wait(forDuration: 1.5)
// Execute the attack
let fire = SKAction.sequence([fireBullet, wait])
run(fire)
}
}
// Create and shoot fireball
func shootFireball(direction: CGVector) {
let fireball = SKSpriteNode(imageNamed: "fireball.png")
fireball.setScale(0.8)
fireball.position = player.position
fireball.zPosition = 1
let waits = SKAction.wait(forDuration: 2.5)
// Lazy validation
if(self.children.count == 1){
// Add fireball node
addChild(fireball)
let moveFireball = SKAction.move(by: direction, duration: 1)
let deleteFireball = SKAction.removeFromParent()
let fireballSequence = SKAction.sequence([moveFireball, deleteFireball])
fireball.run(fireballSequence)
}
}