如何在SWIFT中创建跟随角色的背景?

时间:2015-05-07 14:45:17

标签: swift animation background sprite-kit

我正在Xcode中开展这个项目,我正在制作动画。我有完美的工作程序,小角色走在屏幕周围。如果我按下屏幕,这就是角色的方向。我想在这里做的是添加一个背景图像,让它跟随角色的去向。基本上,我希望角色能够在大地图周围走动而不会离开图像。类似于scrollView,但仅限于gamescene。

P.S。下面的所有代码都有效,我只想添加移动的背景图像。

以下是我的主要gamecene的一些代码

    override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    // the hero is initialized with a texture
    hero = Player(named: "hero_walk_down_0")
    hero.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
    self.addChild(hero)
    if Settings.sharedInstance.virtualPad {
        controller = ControllerNode(position: CGPoint(x:0, y: 0))
        self.addChild(controller)
    }
    backgroundColor = SKColor.blueColor()
}


override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        if Settings.sharedInstance.virtualPad == false {
            hero.destination = location
        }
    }
}

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let previousLocation = touch.previousLocationInNode(self)
        if Settings.sharedInstance.virtualPad == false {
            hero.destination = location
        }
    }
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    touchesEndedOrCancelled(touches, withEvent: event)
}

override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    touchesEndedOrCancelled(touches, withEvent: event)
}

func touchesEndedOrCancelled(touches: NSSet, withEvent event: UIEvent) {
    // when a touch is ended, remove it from the list
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let previousLocation = touch.previousLocationInNode(self)
        if Settings.sharedInstance.virtualPad == false {
            hero.destination = nil
        }
    }
}

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
    if Settings.sharedInstance.virtualPad {
        hero.walk(self.controller!.pressedDirections())
    }
    else {
        if hero.destination != nil {
            hero.walkTowards(hero.destination!)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您创建两个SKNode - 一个用于角色,一个用于背景,并分别添加到每个组。

每当您移动角色的SKNode时,您都会在后台节点上复制相同的操作。