gpt4 book ai didi

swift - 如何使用滑动手势控制 Sprite ,使 Sprite 可以沿 x 轴移动

转载 作者:行者123 更新时间:2023-11-30 10:51:50 25 4
gpt4 key购买 nike

目前我有一个游戏,可以使用设备的加速计控制 Sprite 并沿 x 轴(具有固定的 y 位置)移动。我希望更改此设置,以便用户可以通过在屏幕上拖动来控制 Sprite ,就像在流行游戏(例如贪吃蛇 vs. 方 block )中一样。

我已经尝试使用触摸移动方法,它给出了正确的效果,尽管 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
}

总之,我正在寻找与蛇与 block 相同的控制 Sprite 的方法

最佳答案

嘿,所以你的想法是正确的,你需要存储以前的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
}
}

关于swift - 如何使用滑动手势控制 Sprite ,使 Sprite 可以沿 x 轴移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54381944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com