[英]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.