繁体   English   中英

如何使用滑动手势控制精灵,以便精灵可以沿X轴移动

[英]How to control sprite using swiping gestures so sprite can move along x axis

目前,我有一个游戏,可以使用设备的加速度计控制子画面并使其沿x轴(在y位置固定)移动。 我希望对此进行更改,以便用户可以通过在屏幕上拖动来控制精灵,就像在流行的游戏(如蛇与块)中一样。

我已经尝试过使用touches move方法,该方法可以提供正确的效果,尽管Sprite首先会移动到我不希望的用户触摸位置。

下面是我一直在进行实验的环境,虽然我似乎无法弄清楚如何先将Sprite移至触摸位置,但我似乎无法弄清楚如何停止将Sprite移至触摸位置

import SpriteKit
import GameplayKit

var player = SKSpriteNode()
var playerColor = UIColor.orange
var background = UIColor.black
var playerSize = CGSize(width: 50, height: 50)
var touchLocation = CGPoint()
var shape = CGPoint()
class GameScene: SKScene {

  override func didMove(to view: SKView) {
    self.backgroundColor = background

    spawnPlayer()    
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let touchLocation = touch.location(in: self)
        player.position.x = touchLocation.x
    }
}

func spawnPlayer(){    
    player = SKSpriteNode(color: playerColor, size: playerSize)
    player.position = CGPoint(x:50, y: 500)

    self.addChild(player)
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}

总而言之,我在寻找一种控制蛇形的方法,就像在蛇与块中一样

嘿,所以您有一个正确的主意,您需要存储以前的touchesMovedPoint。 然后使用它来确定每次调用touchMoved时手指已移动了多远。 然后按该数量添加到玩家的当前位置。

var lastTouchLoc:CGPoint = CGPoint()

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let touchLocation = touch.location(in: self)

        let dx = touchLocation.x - lastTouchLoc.x
        player.position.x += dx // Change the players current position by the distance between the previous touchesMovedPoint and the current one.
        lastTouchLoc.x = touchLocation.x // Update last touch location
    }
}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
         // When releasing the screen from point "E" we don't want dx being calculated from point "E".
        // We want dx to calculate from the most recent touchDown point
        let initialTouchPoint =  touch.location(in: self)
        lastTouchLoc.x = initialTouchPoint.x
    }
}

您想使用SKAction.move执行所需的操作。

func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
    return hypot(lhs.x.distance(to: rhs.x), lhs.y.distance(to: rhs.y))
}


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let touchLocation = touch.location(in: self)
        let speed = 100/1  //This means 100 points per second
        let duration = distance(player.position,touchLocation) / speed //Currently travels 100 points per second, adjust if needed
        player.run(SKAction.move(to:touchLocation, duration:duration),forKey:"move")
    }
}

它的作用是在一定时间内将您的“蛇”移动到新位置。 要确定持续时间,您需要弄清楚您的“蛇”要走多快。 我目前已将其设置为移动100点需要1秒的时间,但是您可能需要根据需要进行调整。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM