spritekit适用于制作2D游戏的框架,具备了图形渲染和动画的功能,可以使用图像和精灵(sprite)动起来
不过在创建时不是用 single viewapplication 而是用 game 来创建
创建第一个场景 创建一个自定义的文件,继承自 spritekit
随后加入这段代码
import UIKit //引入spritekit框架 import SpriteKit class HelooScene: SKScene { //当程序转入view后 override func didMoveToView(view: SKView) { createScene() } } //这个函数的功能是用于改变背景的颜色 func createScene() { self.backGroundColor = SKColor.blackColor() }之后只要在gameviewcontroller 中把原来默认的gamescene 改成自定义的文件的文件名即可
if let scene = GameScene(fileNamed:"HelooScene")
在场景中添加问文本
在gameController 中添加文本
class GameViewController: UIViewController { //往场景中添加内容 let myLabel = SKLabelNode(fontNamed: "chalkduster") override func viewDidLoad() { super.viewDidLoad() //设置文本的内容 myLabel.text = "hello" //字体的大小 myLabel.fontSize = 65 //设置文本节点的位置 //添加到场景中 self.addChild(myLabel) if let scene = GameScene(fileNamed:"HelooScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } }
//让文本动起来.响应屏幕点击时间的方法 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { //获取文本的节点 let labelNode = self.childNodeWithName("label") //向上移动的动作 let moveUp = SKAction.moveByX(0, y: 100, duration: 0.5) //放大的动作 let zoom = SKAction.scaleTo(2.0, duration: 0.5) //暂停的动作 let pause = SKAction.waitForDuration(0.5) //淡出的动作 let fadeAwy = SKAction.fadeOutWithDuration(0.25) //执行动作序列 let moveSquence = SKAction.sequence(moveUp,zoom,pause,fadeAwy) //文本开始执行 labelNode.runAction(moveSquence) }
let hover = SKAction.sequence([ SKAction.waitForDuration(0.5), SKAction.moveByX(100, y: 50, duration: 1), SKAction.waitForDuration(1), SKAction.moveByX(-100, y: -50, duration: 1)])添加动作的方法
//以重复的方式进行执行 ship.runAction(SKAction.repeatAction(SKAction.repeatActionForever(hover))) return ship; }
//创建物理系统 ship.physicsBody = SKPhysicsBody(circleOfRadius: 15) //不要让物体消失在底部 ship.physicsBody?.dynamic = false //允许进行碰撞 ship.physicsBody?.usesPreciseCollisionDetection = true
用skshapnode的方法
func newSpaceShip()->SKShapeNode{ //创建一个椭圆,来当飞船 let ship = SKShapeNode() ship.path = CGPathCreateWithRoundedRect(CGRectMake(-15, -15, 30, 30), 15, 15, nil) ship.strokeColor = SKColor.whiteColor() ship.fillColor = SKColor.grayColor() //创建动作,暂停一秒,位移,暂停一秒,位移