2017-07-11 1 views
-2

私はプレーヤーが画面上にボールが入って来ないようにするゲームを作っています。ボールはどんな角度から来ても、プレイヤーが別のボールと接触するとゲームオーバーになります。私の唯一の問題は、プレーヤーの動きです。プレイヤーがヘビのような痕跡を残さずに、有名なスネークゲームのような動きをしたいのです。だから、一定のスピードで一定のスピードで移動し、画面の左側でプレイヤーがタッチすると、プレイヤーは左に、プレイヤーが右側でタッチすると、プレイヤーは右に移動します。しかし、プレーヤーがどちらかの側に触れると、プレーヤーは90度のように動かすべきではありません。どちらか一方に柔らかく動くべきです。したがって、プレーヤーが90度のように動くことを望むならば、彼/彼女は画面上で指を長く押さなければならないでしょう。有名なスネークゲームのようにプレーヤーを動かす

この動画では、プレイヤーの動きを正確に確認できます。プレイヤーが残す跡を無視することはできますが。

ランダムクラス産卵ランダム化されたボール:ここhttps://www.youtube.com/watch?v=GhwaZvsNAA0

あなたは私のコードを持っている

import Foundation 
import CoreGraphics 

public extension CGFloat { 

public static func randomBetweenNumbers(firstNum: CGFloat, secondNum: 
CGFloat) -> CGFloat { 

    return CGFloat(arc4random())/CGFloat(UINT32_MAX) * abs(firstNum - 
secondNum) + firstNum 

} 

} 

プレイヤークラス:

import SpriteKit 

struct ColliderType { 

static let Player: UInt32 = 1 
static let Score: UInt32 = 2 
static let Enemy: UInt32 = 3 

} 

class Player: SKSpriteNode { 

func initialize() { 
    self.name = "Player" 
    self.zPosition = 1 
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.height/
2) 
    self.physicsBody?.affectedByGravity = false 
    self.physicsBody?.categoryBitMask = ColliderType.Player 
    self.physicsBody?.collisionBitMask = ColliderType.Enemy 
    self.physicsBody?.contactTestBitMask = ColliderType.Score | 
ColliderType.Enemy 
} 

} 

これはgameplaysceneクラスは次のとおりです。

import SpriteKit 

class GameplayScene: SKScene, SKPhysicsContactDelegate { 

var player = Player() 

var ball = SKSpriteNode() 

var ballIsTouched = false 

var scoreLabel = SKLabelNode() 
var score = 0 

var counter = Timer() 

override func didMove(to view: SKView) { 
    initialize() 
} 

override func update(_ currentTime: TimeInterval) { 

} 

override func touchesBegan(_ touches: Set<UITouch>, with event: 
UIEvent?) { 


    for touch in touches { 

     let location = touch.location(in: self) 

     if atPoint(location).name == "Retry" { 
      self.removeAllActions() 
      self.removeAllChildren() 
      initialize() 
     } 

     if atPoint(location).name == "Quit" { 
      let mainmenu = MainMenuScene(fileNamed: "MainMenuScene") 
      mainmenu!.scaleMode = .aspectFill 
      self.view?.presentScene(mainmenu!, transition: 
SKTransition.fade(withDuration: TimeInterval(1))) 
     } 

    } 

} 

func didBegin(_ contact: SKPhysicsContact) { 

    var firstBody = SKPhysicsBody() 
    var secondBody = SKPhysicsBody() 

    if contact.bodyA.node?.name == "Player" { 
     firstBody = contact.bodyA 
     secondBody = contact.bodyB 
    } else { 
     firstBody = contact.bodyB 
     secondBody = contact.bodyA 
    } 

    if firstBody.node?.name == "Player" && secondBody.node?.name == 
"Score" { 
     incrementCoinScore() 
     secondBody.node?.removeFromParent() 
    } 

    if firstBody.node?.name == "Player" && secondBody.node?.name == 
"Enemy" { 
     playerDied() 
     firstBody.node?.removeFromParent() 
    } 

} 

func initialize() { 

    score = 0 

    physicsWorld.contactDelegate = self 

    createPlayer() 
    createBackground() 
    spawnEnemy1() 
    spawnEnemy2() 
    spawnEnemy3() 
    spawnEnemy4() 
    createLabel() 

    counter = Timer.scheduledTimer(timeInterval: TimeInterval(1), 
target: self, selector: "incrementScore", userInfo: nil, repeats: true) 
} 

func createPlayer() { 
    player = Player(imageNamed: "Player") 
    player.initialize() 
    player.position = CGPoint(x: 0, y: 0) 
    self.addChild(player) 
} 

func createBackground() { 
    let bg = SKSpriteNode(imageNamed: "BG") 
    bg.name = "BG" 
    bg.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    bg.position = CGPoint(x: 0, y: 0) 
    self.addChild(bg) 
} 

func createEnemy1() { 
    let ball = SKSpriteNode(imageNamed: "Orange") 
    ball.name = "Enemy" 
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    ball.zPosition = 1 
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height/
2) 
    ball.physicsBody?.categoryBitMask = ColliderType.Enemy 
    ball.physicsBody?.affectedByGravity = false 
    ball.physicsBody?.isDynamic = false 

    ball.position.y = self.size.height + 100 
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345, 
secondNum: 345) 

    self.addChild(ball) 

    let destination = self.frame.height * 2 
    let move = SKAction.moveTo(y: -destination, duration: 
TimeInterval(10)) 
    let remove = SKAction.removeFromParent() 

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveEnemy1") 
} 

func spawnEnemy1() { 

    let spawn = SKAction.run({() -> Void in 
     self.createEnemy1() 
    }) 

    let delay = SKAction.wait(forDuration: TimeInterval(1)) 
    let sequence = SKAction.sequence([spawn, delay]) 

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnEnemy1") 
} 

func createEnemy2() { 
    let ball = SKSpriteNode(imageNamed: "Green") 
    ball.name = "Enemy" 
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    ball.zPosition = 1 
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height/
2) 
    ball.physicsBody?.categoryBitMask = ColliderType.Enemy 
    ball.physicsBody?.affectedByGravity = false 
    ball.physicsBody?.isDynamic = false 

    ball.position.y = -self.size.height + 100 
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345, 
secondNum: 345) 

    self.addChild(ball) 

    let destination = self.frame.height * 2 
    let move = SKAction.moveTo(y: destination, duration: 
TimeInterval(10)) 
    let remove = SKAction.removeFromParent() 

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveEnemy2") 
} 

func spawnEnemy2() { 

    let spawn = SKAction.run({() -> Void in 
     self.createEnemy2() 
    }) 

    let delay = SKAction.wait(forDuration: TimeInterval(1)) 
    let sequence = SKAction.sequence([spawn, delay]) 

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnEnemy2") 
} 

func createEnemy3() { 
    let ball = SKSpriteNode(imageNamed: "Blue") 
    ball.name = "Enemy" 
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    ball.zPosition = 1 
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height/
2) 
    ball.physicsBody?.categoryBitMask = ColliderType.Enemy 
    ball.physicsBody?.affectedByGravity = false 
    ball.physicsBody?.isDynamic = false 

    ball.position.x = -self.size.width + 200 
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637, 
secondNum: 637) 

    self.addChild(ball) 

    let destination = self.frame.height * 2 
    let move = SKAction.moveTo(x: destination, duration: 
TimeInterval(10)) 
    let remove = SKAction.removeFromParent() 

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveEnemy3") 
} 

func spawnEnemy3() { 

    let spawn = SKAction.run({() -> Void in 
     self.createEnemy3() 
    }) 

    let delay = SKAction.wait(forDuration: TimeInterval(1)) 
    let sequence = SKAction.sequence([spawn, delay]) 

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnEnemy3") 
} 

func createEnemy4() { 
    let ball = SKSpriteNode(imageNamed: "Yellow") 
    ball.name = "Enemy" 
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    ball.zPosition = 1 
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height/
2) 
    ball.physicsBody?.categoryBitMask = ColliderType.Enemy 
    ball.physicsBody?.affectedByGravity = false 
    ball.physicsBody?.isDynamic = false 

    ball.position.x = self.size.width + 200 
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637, 
secondNum: 637) 

    self.addChild(ball) 

    let destination = self.frame.height * 2 
    let move = SKAction.moveTo(x: -destination, duration: 
TimeInterval(10)) 
    let remove = SKAction.removeFromParent() 

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveEnemy4") 
} 

func spawnEnemy4() { 

    let spawn = SKAction.run({() -> Void in 
     self.createEnemy4() 
    }) 

    let delay = SKAction.wait(forDuration: TimeInterval(1)) 
    let sequence = SKAction.sequence([spawn, delay]) 

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnEnemy4") 
} 


func createLabel() { 
    scoreLabel.zPosition = 3 
    scoreLabel.position = CGPoint(x: -320, y: 600) 
    scoreLabel.fontName = "Verdana" 
    scoreLabel.fontSize = 70 
    scoreLabel.text = "0" 
    self.addChild(scoreLabel) 
} 

func incrementScore() { 
    score += 1 
    scoreLabel.text = String(score) 
} 

func incrementCoinScore() { 
    score += 5 
} 

func playerDied() { 

    counter.invalidate() 

    let highscore = GameManager.instance.getHighscore() 

    if highscore < score { 
     GameManager.instance.setHighscore(highscore: score) 
    } 

    let retry = SKSpriteNode(imageNamed: "Retry") 
    let quit = SKSpriteNode(imageNamed: "Quit") 

    retry.name = "Retry" 
    retry.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    retry.position = CGPoint(x: -150, y: -50) 
    retry.zPosition = 2 
    retry.setScale(0) 

    quit.name = "Quit" 
    quit.anchorPoint = CGPoint(x: 0.5, y: 0.5) 
    quit.position = CGPoint(x: 150, y: -50) 
    quit.zPosition = 2 
    quit.setScale(0) 

    let scaleUp = SKAction.scale(to: 1, duration: TimeInterval(0.5)) 

    retry.run(scaleUp) 
    quit.run(scaleUp) 

    self.addChild(retry) 
    self.addChild(quit) 

} 

} 

答えて

0

あなたが何を理解しているか、私はあなたの質問を2,3回読まなければなりませんでした。しかし、私は "achtung die curve"をバックにしていたので、ついにそれを感知しました。ここにあなたが望むものの実例があります。コピー - 貼り付け - theresの何かが、あなたは完全に

class Player: SKSpriteNode { 

    let playerSpeed = 3 
    let turnRate:CGFloat = 0.03 
    var isAlive = true 

    // this is the initializer for the class. when you make an instance 
    // of your class, this function will be called. and this is were you setup your player. 
    init() { 

    //create a texture for your player 
    let texture = SKTexture(imageNamed: "player") 
    //setup other stuff you already have in your own code. 
    // when you create an instance in your createPlayer function do like this 
    // let player = Player() 
    // player.position = CGPoint(x: 0, y: 0) 
    //self.addChild(player) 

    // note that you do not need to call the init manually. 

    // since your player class is an subclass of SKSpriteNode you have to call super.init(). 
    // This is the initializer of your superclass (SKSpriteNode), 
    // I would suggest you read more about subclassing and this will make sens. 
     super.init(texture: texture, color: UIColor.clear, size:texture.size()) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 


    func turnLeft(){ 

     // add to the current rotation by a factor of turnRate 
     self.run(SKAction.rotate(byAngle: turnRate, duration: 0)) 

    } 

    func turnRight(){ 

     // subtract from the current rotation by a factor of turnRate 
     self.run(SKAction.rotate(byAngle: -turnRate, duration: 0)) 

    } 

    func move(){ 

     // this gives us a position in the scene space that is 3 points(or what ever value playerSpeed is) 
     // infront of the player. basicly we convert (x:0, y:3) from the player coordinates. to the scene coordinate. 
     // Even when the player rotates in the scene. the (x:0, y:3) is allways the same in the player coordinate. 
     let newPosition = convert(CGPoint(x:0, y:playerSpeed), to: scene!) 
     self.position = newPosition 

    } 


} 

class GameScene: SKScene { 

    let player = Player() 

    var shouldTurnLeft = false 
    var shouldTurnRight = false 

    override func didMove(to view: SKView) { 


     addChild(player) 


    } 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

     let touchLocation = touches.first?.location(in: self) 

     if (touchLocation?.x)! > 0{ 

      shouldTurnRight = true 
     } 
     else if (touchLocation?.x)! < 0{ 

      shouldTurnLeft = true 

     } 

    } 


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     shouldTurnLeft = false 
     shouldTurnRight = false 
    } 


    override func update(_ currentTime: TimeInterval) { 

     // if the player is alive. move the player every frame 
    if player.isAlive{ 
     player.move() 

     if shouldTurnLeft { 
      player.turnLeft() 
     } 
     if shouldTurnRight{ 
      player.turnRight() 
     } 
    } 




     // Called before each frame is rendered 
    } 
} 
+0

感謝を理解していないかどうかを調べる

が尋ねるお気軽に!私は1つの問題がある。コードを追加すると、createPlayer関数からエラーが発生しました。より正確には、「player = Player(imageNamed: "Player")」という行にあります。 Swiftは "imageNamed"を "コーダー"に変更したいと思っていますが、私は同じ行に "文字列型の値を"引数型 "NSCoder"に変換できないという別の問題があります。それを修正する方法はありますか? – Flinigan

+0

ええ、よくあなたのコードは、実際にはコードと互換性がありません私の答えです。私が意味していたのは、新しい空のプロジェクトに自分のコードをコピーすると、それがうまく動作するように記述したように機能するということでした。それがどのように動作するかを評価してから、あなたのコードに合うようにコンセプトをカスタマイズしてください。 –

+0

これはあなたの現在のコードで問題になっています:createPlayer関数でプレーヤークラスのインスタンスを作成するときです。イメージをパラメータとして提供しようとします。 player = Player(imageNamed: "Player")。プレイヤークラスでは、init関数内のパラメーターを受け入れません。正直言って私は前にinitialize()も見たことがありません。標準のinitだけです。どのように見えるかについてのいくつかの洞察を与えるために私の答えを更新します:) –

関連する問題