我有这个代码,我正在尝试编写游戏。当屏幕右侧有一个水龙头时,我希望汽车在一条车道右转,当屏幕左侧有一个水龙头时,我想要离开一条车道。我写了一个移动汽车的功能,但我不知道如何让它工作。这是我的代码:
//
// GameScene.swift
// cargame
//
// Created by Pranav Sharan on 3/21/17.
// Copyright © 2017 Pranav Sharan. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let player:SKSpriteNode = self.childNode(withName: "car") as! SKSpriteNode
}
func touchDown(atPoint pos : CGPoint) {
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let position = touch.location(in: self)
print(position.x)
print(position.y)
if position.x < 0 {
moveLeft(object: player)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
func moveLeft(object: SKSpriteNode){
let move = SKAction.moveTo(x: -20, duration: 0.5)
object.run(move)
}
}
答案 0 :(得分:0)
以下是一个如何完成此操作的示例,希望它有所帮助。
class GameScene: SKScene {
var player = SKSpriteNode()
override func didMove(to view: SKView) {
player = SKSpriteNode(color: .purple, size: CGSize(width: 100, height: 100))
player.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(player)
}
func touchDown(atPoint position : CGPoint) {
if position.x < self.frame.midX
{
let move = SKAction.moveTo(x: self.frame.minX + 200, duration: 0.3)
player.run(move)
} else if position.x > self.frame.midX {
let move = SKAction.moveTo(x: self.frame.maxX - 200, duration: 0.3)
player.run(move)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
}
如果触摸小于屏幕中间,则屏幕中间由self.frame.midX定义。
答案 1 :(得分:0)
我看到的第一件事是你在didMove()函数中声明你的玩家节点,这使得它在该函数范围之外不可见。
将玩家节点声明为GameScene类的属性,以使其在课堂内外的任何地方都可用。然后,将场景对象分配给它。你的代码更像是这样:
class GameScene: SKScene {
var player:SKSpriteNode
override func didMove(to view: SKView) {
self.player = self.childNode(withName: "car") as! SKSpriteNode
}