【发布时间】:2015-08-21 14:48:50
【问题描述】:
我正在尝试创建一个类似于this question 中的“奖轮”的可旋转节点。到目前为止,我有投掷能力,使用 UIPanGestureRecognizer 在物理体上添加角度脉冲,效果非常好。我也可以通过触摸停止旋转。
现在我尝试允许使用拖动或滑动手势微调滚轮,因此如果玩家对最终的结果不满意,他们可以手动旋转/拖动/旋转到他们喜欢的旋转。
目前我将触摸的位置保存在 touchesBegan 中,并尝试在更新循环中增加我的节点的 zRotation。
旋转不跟随我的手指并且是生涩的。我不确定我是否对手指运动有足够准确的读数,或者手指的变化位置是否没有准确地转换为弧度。我怀疑检测到触摸然后在更新中处理它不是一个很好的解决方案。
这是我的代码。
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent?) {
if let touch = touches.first as? UITouch {
var location = touch.locationInView(self.view)
location = self.convertPointFromView(location)
mostRecentTouchLocation = location
let node = nodeAtPoint(location)
if node.name == Optional("left") && node.physicsBody?.angularVelocity != 0
{
node.physicsBody = SKPhysicsBody(circleOfRadius:150)
node.physicsBody?.applyAngularImpulse(0)
node.physicsBody?.pinned = true
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if mostRecentTouchLocation != CGPointZero{
let node = nodeAtPoint(mostRecentTouchLocation)
if node.name == Optional("left")
{
var positionInScene:CGPoint = mostRecentTouchLocation
let deltaX:Float = Float(positionInScene.x) - Float(node.position.x)
let deltaY:Float = Float(positionInScene.y) - Float(node.position.y)
let angle:CGFloat = CGFloat(atan2f(deltaY, deltaX))
let maths:CGFloat = angle - (CGFloat(90) * (CGFloat(M_PI) / 180.0))
node.zRotation += maths
mostRecentTouchLocation = CGPointZero
}
}
}
我在更新中将一些数学分布分布在多行中,以使调试更容易一些。
如果需要,我可以添加 PanGestureRecognizer 代码,但我会尽量保持简短。
编辑 这是我基于 GilderMan 推荐的最新代码。我认为它工作得更好,但旋转远非顺利。它的跳跃幅度很大,并且没有很好地跟随手指。这是否意味着我的角度计算有问题?
override func didSimulatePhysics() {
if mostRecentTouchLocation != CGPointZero {
let node = nodeAtPoint(mostRecentTouchLocation)
if node.name == Optional("left")
{
var positionInScene:CGPoint = mostRecentTouchLocation
let deltaX:Float = Float(positionInScene.x) - Float(node.position.x)
let deltaY:Float = Float(positionInScene.y) - Float(node.position.y)
let angle:CGFloat = CGFloat(atan2f(deltaY, deltaX))
node.zRotation += angle
println(angle)
mostRecentTouchLocation = CGPointZero
}
}
}
【问题讨论】:
-
你原帖的角度转换没有问题
-
所以 atan2f 结果是以弧度为单位的,这是添加到 zRotation 的正确单位?
-
是的,
zRotation和atan2f的单位是弧度
标签: swift sprite-kit