Skip to content

Instantly share code, notes, and snippets.

@muzahid59
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save muzahid59/eeac3b68a332eca99c64 to your computer and use it in GitHub Desktop.

Select an option

Save muzahid59/eeac3b68a332eca99c64 to your computer and use it in GitHub Desktop.
Swift: Shoot Sprite at the specific direction
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
#if !(arch(x86_64) || arch(arm64))
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let touchLocation = touch.locationInNode(self)
let projectile = SKSpriteNode(imageNamed: "projectile")
// add projectile to shooter location
projectile.position = shooter.position // set projectile to the shooter postion
self.addChild(projectile)
let offset = touchLocation - projectile.position
if offset.x < 0 { return }
// calculate the direction to shoot
let direction = offset.normalized()
// add enough so that projectile pass the screen
let shootAmount = direction * 1000
// set the projectile direction from shooter
let realDistance = shootAmount + projectile.position
let actionMove = SKAction.moveTo(realDistance, duration: 1)
let actionDone = SKAction.removeFromParent()
projectile.runAction(SKAction.sequence([actionMove,actionDone]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment