美文网首页iOSSpriteKit
Sprite Kit游戏开发

Sprite Kit游戏开发

作者: CYC666 | 来源:发表于2022-01-07 21:22 被阅读0次

    《Sprite Kit 开发学习01》

    二、场景

    4、滚动场景

    //“+”加法运算符的重载

    func + (left: CGPoint, right: CGPoint) -> CGPoint {

        return CGPoint(x: left.x + right.x, y: left.y + right.y)

    }

    //“+=”赋值加法运算符的重载

    func += (inout left: CGPoint, right: CGPoint) {

        left = left + right

    }

    //“*”乘法运算符的重载

    func * (point: CGPoint, scalar: CGFloat) -> CGPoint {

        return CGPoint(x: point.x * scalar, y: point.y * scalar)

    }

    三、精灵

    3.4.1 改变精灵的位置

            splash.position = CGPointMake(CGRectGetMidX(self.frame), 

            CGRectGetMidY(self.frame))

    3.4.2 设置锚点

            splash.anchorPoint=CGPointMake(1.0, 0.5)

    3.4.3 为精灵着色        splash.color=SKColor.greenColor()        splash.colorBlendFactor=0.5    影响

    3.4.5 调整尺寸

            splash.size=CGSizeMake(1440, 900)

    3.4.6 缩放精灵

            splash.setScale(4.0)    x、y一起缩放

            splash.xScale=2    

            splash.yScale=2

    3.4.7 旋转精灵

            splash.zRotation=CGFloat(M_PI)

    3.4.7 设置精灵的透明度

            splash.alpha=0.5

    3.4.8 隐藏精灵

            splash.hidden=true

    3.5.1 删除指定精灵

            sprite2.removeFromParent()

    3.5.2 删除所有精灵

            self.removeAllChildren()

    3.6 让精灵更有真实感

    SKLightNode

    enabled 光源开关

    ambientColor 环境色,默认是黑色,也就没有环境色

    lightColor 光的颜色,默认白色

    shadowColor 被精灵遮挡产生的阴影颜色

    falloff 光源强度的衰减比例

    categoryBitMask 光的种类

    3.7 移动精灵

    override func update(currentTime: CFTimeInterval) {

      //判断lastUpdateTime是否大于0

        if lastUpdateTime > 0 {

            dt = currentTime - lastUpdateTime

        } else {

            dt = 0

        }

        lastUpdateTime = currentTime

        moveSprite(sprite, velocity: velocity)

    }

    3.8 纹理 SKTexture

    四、动作    SKAction

    4.1.1 以点的方式移动(指定到那个点) moveTo、moveToX、moveToY

    let actionMove = SKAction.moveTo(

                CGPoint(x: 100, y: sprite.position.y),

                duration: 5)

    sprite.runAction(actionMove)

    4.1.2 以偏移量的方式移动(将会移动多远) moveBy、moveByX、moveByY

    let negDelta = CGVectorMake(-820,-430)

            let actionMove = SKAction.moveBy(negDelta, duration: 5)

            sprite.runAction(actionMove)

    4.2 序列动作

    let sequence = SKAction.sequence([actionMidMove, actionMove])            sprite.runAction(sequence)

    4.3 重复动作

    4.3.1 无限重复

    let sequence = SKAction.sequence([leftMove, rightMove])            

    var runForever=SKAction.repeatActionForever(sequence)   

    4.3.2 具有次数的重复

    runrepeat=SKAction.repeatAction(sequence, count: 3)

    4.4 延迟动作

    wait1=SKAction.waitForDuration(1.0)    等待动作

    let wait3=SKAction.waitForDuration(1.0,withRange: 2.0)

    4.5 缩放动作

    4.5.1 以缩放倍数缩放 scaleTo、scaleXTo、scaleYTo

    let zoom = SKAction.scaleTo(1, duration: 0.2)   

    4.5.2 以增量值缩放

    let zoom = SKAction.scaleBy(1, duration: 0.2)                      //放大

    let shrink=SKAction.scaleBy(-1, duration: 0.2)  

    4.6 旋转动作

    let rotate=SKAction.rotateByAngle(CGFloat(M_PI)*2 , duration: 3)

    4.7 调整尺寸的动作(类似于缩放动作)

    4.7.1 以目标值调整尺寸

    let resize=SKAction.resizeToWidth(500, height: 500, duration: 5)

    4.7.2 以增量调整尺寸

    let resize=SKAction.resizeByWidth(300, height:300, duration: 5)

    4.8 组合动作(同时对两个或者两个以上的动作进行执行)

    let zoom = SKAction.scaleTo(1, duration: 0.2)

    let shrink = SKAction.scaleTo(0.1, duration: 0.2)

    let sequence = SKAction.sequence([zoom,shrink])

    let rotate = SKAction.rotateByAngle(CGFloat(M_PI)*2 , duration: 1.5)  let group = SKAction.group([sequence, rotate]) 

    4.9 改变透明度的动作

    4.9.1 不需指定alpha值

    let fadeOut=SKAction.fadeOutWithDuration(0.25)                      //隐藏

    let fadeIn=SKAction.fadeInWithDuration(0.25)                        //显示

    4.9.2 指定alpha值

    let hide=SKAction.fadeAlphaTo(0, duration: 0.2)                        //隐藏

    let hide=SKAction.fadeAlphaBy(-1, duration: 0.2)

    4.10 改变颜色的动作

    4.10.1 改变混合因子

    let color1=SKAction.colorizeWithColorBlendFactor(0.8, duration: 0.5)

    4.10.2 改变颜色和混合因子

    let color=SKAction.colorizeWithColor(SKColor.greenColor(), colorBlend Factor: 0.7, duration: 2)

    👍

    《Sprite Kit 开发学习02》

    4.11 以动画的形式改变纹理的动作

    //加载走路动画的纹理

            var f1=SKTexture(imageNamed: "Player_Right1.png")

            var f2=SKTexture(imageNamed: "Player_Right2.png")

            var f3=SKTexture(imageNamed: "Player_Right3.png")

            var f4=SKTexture(imageNamed: "Player_Right4.png")

            var textureArray=[f1,f2,f3,f4]

    var runRightAction=SKAction.animateWithTextures(textureArray, timePerFrame: 0.1)

    4.12 路径动作(一般是相对于游戏中敌人而言的,不受玩家的控制,沿某一路径进行运动)

    let screenBorders = CGPathCreateWithRect(playableRect, nil)

    let follow1=SKAction.followPath(screenBorders, duration: 10.0)

    let circle = CGPathCreateWithRoundedRect(CGRectMake(550, 200, 400, 400), 200, 200, nil)

    let follow2=SKAction.followPath(circle, asOffset: false, orientToPath: false, duration: 10.0)

    4.13 反向运动(不是所有动作都可以进行反向运行。有时候会返回一个什么也不做的动作,或者会返回一个与原始动作相同的动作。)

    let actionMove = SKAction.moveByX(-400, y: 0, duration: 5)

    let reversed=actionMove.reversedAction()                                  //反向动作

    sprite.runAction(reversed())

    4.14 速度动作(改变场景中精灵或者其他节点执行动作的速度)

    let speedaction=SKAction.speedTo(5, duration: 1.0)  

    let group=SKAction.group([speedaction,moveto,scaleto])

    4.15 显示或隐藏动作

    unhide、hide

    4.16 块动作

    let block = SKAction.funBlock() {

        // 动作

    }

    4.17 自定义动作 customActionWithDuration

    4.18 动作属性

    1、速度 speed

    2、时间 duration

    3、曲线方式 timingMode(Linear、EaseIn、、、)

    4.19 删除动作 

    var remove=SKAction.removeFromParent()  

    五、用户交互

    5.1 触摸

    5.1.1 轻拍触摸 touchesBegan()

    var touch: AnyObject?=mytouches.anyObject()

            //判断是否为单拍

            if(touch?.tapCount==1){

            //判断是否为连续轻拍2次

            if(touch?.tapCount==2){

    5.1.2 移动触摸 touchesMoved() 

    5.1.3 结束触摸和取消触摸 touchesMoved()、touchesCancelled()

    5.2 手势

    5.2.1 轻拍

    let tapGestureRecognizer=UITapGestureRecognizer(target: self, action: "handleTap") self.view?.addGestureRecognizer(tapGestureRecognizer)   

    5.2.2 捏

    UIPinchGestureRecognizer

    5.2.3 旋转

    UIRotationGestureRecognizer

    5.2.4 移动

    UIPanGestureRecognizer

    5.2.5 滑动

    UISwipeGestureRecognizer

    5.2.6 长按

    UILongPressGestureRecognizer

    5.3 重力感应

    if((self.mManager?.accelerometerAvailable) == true){

            //重力感应可用

    六、游戏中的文字

    6.1.2 使用代码实现标签

    let myLabel = SKLabelNode(text: "Hello")

    6.2 设置标签

    1、文字大小 fontSize

    2、颜色 fontColor

    3、文字 text

    4、文字的字体 fontName

    6.3 自定义字体

    6.4 标签的对齐方式

    1、水平 

    myLabel1.verticalAlignmentMode=SKLabelVerticalAlignmentMode.Center  

    2、垂直

    myLabel1.horizontalAlignmentMode=SKLabelHorizontalAlignmentMode.

    Center

    6.5 为标签添加动作

    七、音视频 (音频=背景音乐+音效)

    7.1 背景音乐

    1、添加背景音乐以及播放

            var path=NSBundle.mainBundle().pathForResource("backgroundMusic",          ofType: "mp3")

            var pathURL=NSURL.fileURLWithPath(path!)

            audioEffect=AVAudioPlayer(contentsOfURL: pathURL,error: nil)                                        audioEffect?.play()

    2、控制背景音乐

    play() 播放

    pause() 暂停

    stop() 停止

    3、设置播放点 currentTime

    4、设置音量 volume

    5、循环播放AVAudioPlayer numberOfLoops 这里的3表示背景音乐循环了4次,0表示背景音乐第一次播放

    👍

    《Sprite Kit 开发学习03》

    7.2 音效 

    1、

    AudioToolbox.framework

    var file=NSBundle.mainBundle().pathForResource("1", ofType: "mp3"AudioServicesCreateSystemSoundID(NSURL.fileURLWithPath(file!), &systemsoundID)AudioServicesPlaySystemSound(systemsoundID)

    2、

    let playsound=SKAction.playSoundFileNamed("拨动树枝音效.wav",waitForCompletion: false)

    runAction(playsound)

    SKAction类中的playSoundFileNamed()方法除了可以播放音效外,还可以用来播放背景音乐。

    7.3 视频

    1、播放视频

    SKVideoNode(mov、qt、mp4、m4v、3gp、3gpp)

    let videoNode: SKVideoNode=SKVideoNode(AVPlayer: player) 

    2、控制视频

    play()

    pause()

    八、粒子系统

    8.1 使用例子系统编辑器添加粒子系统 SproteKit Particle File

    Bokeh 背景虚化

    Fire 火焰

    FireFiles 萤火虫

    Magic 魔幻

    Rain 下雨

    Smoke 烟雾

    Snow 下雪

    Spark 火花

    8.2 使用场景编辑器实现添加粒子系统 GameSence.sks、Emitter

    8.3 粒子发射器参数说明

    Backgroud 背景

    Particle Texture 粒子的纹理

    Particles 开始、最大数量

    LifeTime 生命周期、存活时间范围

    Position Range 发射位置范围

    Angle 角度

    Speed 速度

    Acceleration 加速度

    Scale 大小

    Rotation 旋转角度

    Color Blend 颜色混合度

    Color Ramp 粒子的颜色梯度

    Blend Mode 混合模式

    8.4 使用代码实现粒子系统

    //触摸实现下雪的效果

        override func touchesBegan(touches: Set<NSObject>, withEvent event:        UIEvent) {

            let rainTexture = SKTexture(imageNamed: "snow.png")

            let emitterNode = SKEmitterNode()

            emitterNode.particleTexture = rainTexture

            emitterNode.particleBirthRate = 80.0        //设置每秒创建的粒子数

            emitterNode.particleColor = SKColor.whiteColor()    //粒子的颜色

            emitterNode.particleSpeed = -450                    //粒子的平均初始速度

            emitterNode.particleSpeedRange = 150//粒子的初始速度,这个值是一个允许的值域范围内的随机值

            emitterNode.particleLifetime = 2.0          //粒子的生命周期

            emitterNode.particleScale = 0.2                    //粒子的平均缩放因子

            emitterNode.particleAlpha = 0.75                    //粒子的平均初始alpha值

            emitterNode.particleAlphaRange = 0.5

            emitterNode.particleColorBlendFactor = 1//一个平均的初始值,用作颜色混合因子

            emitterNode.particleScale = 0.2

            emitterNode.particleScaleRange = 0.5        //设置发射器的位置

            emitterNode.position = CGPoint(

                x: CGRectGetWidth(frame) / 2, y: CGRectGetHeight(frame) + 10)

            //粒子的初始位置,这个值是一个允许的值域范围内的随机值

            emitterNode.particlePositionRange =

                CGVector(dx: CGRectGetMaxX(frame), dy: 0)

            addChild(emitterNode)

        }

    8.5 使用关键帧序列配置粒子属性

    下雨效果

    8.6 给粒子添加动作

    1、runAction()

    2、particleAction()

    不停出现又消失的小星星

    let color=SKAction.colorizeWithColor(SKColor.greenColor(), color BlendFactor: 0.7, duration: 2)

    emitterNode.particleAction=color

    8.7、重置粒子系统

    resetSimulation()

    👍

    《Sprite Kit 开发学习04》

    九、SpriteKit中其它节点

    9.1 修剪节点 SKCropNode,主要用于遮罩

    9.2 形状节点 SKShapeNode

    不带圆角

    var rect=SKShapeNode(rect: CGRectMake(400, 300, 200, 200))

    addChild(rect)

    带圆角

    var rect=SKShapeNode(rect: CGRectMake(400, 300, 200, 200),corner Radius: 20)

    圆形

    var circular=SKShapeNode(circleOfRadius: 100)

    circular.position=CGPointMake(500, 400)

    椭圆

    var circular=SKShapeNode(ellipseInRect: CGRectMake(350, 300, 300, 200))

    9.2.3 个性化形状

    1、lineWidth 线宽

    2、strokeColor 线条颜色

    3、glowWidth 光晕

    4、fillColor 填充颜色

    9.2.4 设置形状的路径 SKShapeNode path

    绘制路径

    var path:CGMutablePathRef = CGPathCreateMutable()

    CGPathMoveToPoint(path, nil, 0.0, 0.0)

    CGPathAddLineToPoint(path, nil, 600, 600)

    9.3 效果节点

    SKEffectNode 滤镜

    十、物理引擎与碰撞

    10.3

    1、物理体:动态体积、静态体积、边

    2、创建简单物理体:矩形、圆形、size

    var physicsBody=SKPhysicsBody(rectangleOfSize: mylabel.frame.size)            mylabel.physicsBody=physicsBody 

    3、自定义物理体

    triangle.physicsBody = SKPhysicsBody(polygonFromPath: trianglePath)

    4、添加边界

    self.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRectMake(self.frame.origin.x, self.frame.origin.y+90, self.frame.size.width, self.frame. size.height))

    5、可视化物理体

    10.4 物理引擎的属性设置 SKPhysicsBody

    10.5 

    1、让物理体进行移动(施加力)

    applyForce()    均匀作用于物理体的拉力

    applyTorque()    侧向推力

    applyImpulse()  均匀作用于物理体的推力   

    applyAngularImpulse()    角度力

    2、默认的力:重力、阻力、摩擦力

    10.6 物理体的连接

    1、关联类

    SKPhyysicsFixed 固定联合,可以打散

    SKPhysicsJoinSliding    滑动联合

    SKPhysicsJoinSpring    弹簧联合

    SKPhysicsJoinLimit    界限联合

    SKPhysicsJoinPin    针联合

    2、使用物理联合

    A、创建两个物理体

    B、把物理体附加到场景中的一对SKNode

    C、使用上面列出的子类创建一个联合对象

    D、配置联合对象属性

    E、调用物理世界的addJoin方法

    10.7 在游戏中的碰撞

    1、最简单的碰撞 if语句

    2、物理引擎碰撞 

    SKPhysicsContactDelegate 

    self.physicsWorld.contactDelegate=self  

    didBeginContact() 

    十一、瓦片地图

    二维数组

    11.2 设置瓦片地图

    1、缩放模式

    scene.scaleMode = .ResizeFill    

    2、过滤模式(在进行缩放显示时让纹理进行平滑处理的一种方式)

    sprite.texture?.filteringMode = .Nearest

    3、点到地图

    4、随机生成瓦片

    11.5 滚动地图

    👍

    相关文章

      网友评论

        本文标题:Sprite Kit游戏开发

        本文链接:https://www.haomeiwen.com/subject/obrscrtx.html