繁体   English   中英

如何使精灵的速度相同?

[英]How to make speed of sprite same?

我开始使用 Swift 语言编写一个简单的游戏来提高我在 Xcode 中的 SpriteKit 技能。 在我的游戏中,只有一个精灵会在我点击屏幕的地方改变它的位置。 我是这样做的:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
    ZombieNode.run (SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: 1))
 }
}

但只有一个问题,我的精灵速度取决于我点击的位置。 所以我明白为什么 - 因为精灵应该在一秒钟内改变位置,所以如果我远离我的精灵点击速度会更快,如果我点击靠近精灵的速度非常低。 所以我的问题是 - 如何做同样的速度? 也许我应该使用其他功能而不是

 ZombieNode.run (SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: 1))

或者也许有一些数学公式可以做到这一点。 所以请帮帮我,我怎样才能让速度到处都一样?

您需要先进行距离检查,然后将持续时间乘以距离系数。

使用 x 2 + y 2 = 距离2 的勾股定理

let deltaX = location.x - current.x
let deltaY = location.y - current.y

let distance = (deltaX * deltaX + deltaY * deltaY).squareRoot()

Then you can get a ratio, using the distance you'd like to travel in a second.  For example, if you'd like to move at 400 pixels per second you could do the following:

let pixelsPerSecond = 400

let timeToTravel = distance/pixelsPerSecond

然后利用时间来这里旅行:

ZombieNode.run (SKAction.move(to: CGPoint(x: location.x, y: location.y), duration: timeToTravel))

暂无
暂无

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

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