代码:
for touch in touches{
let location = touch.location(in: self)
let maxTouchHeight = self.frame.midY
if currentGameType == .wobble{
main.zRotation = (location.y)/512
if location.y > maxTouchHeight { return }
}
}
}
因此,在一种乒乓游戏中,我尝试根据手指在 y 轴上的位置来旋转 Racket 。但是,我无法做到它只能在屏幕的下半部分工作,即旋转的两个末端位于屏幕的最顶部和最底部,但我希望顶部位于屏幕的顶部屏幕的下半部分。 (主要是乒乓 Racket )。
感谢任何帮助:)
最佳答案
经过评论的讨论和反复的答案更新,我为您提供了一个解决方案。如果有问题,请告诉我:
class GameScene: SKScene {
let paddle = SKSpriteNode()
let maximumRotation = CGFloat(45)
override func didMove(to view: SKView) {
paddle.color = .blue
paddle.size = CGSize(width: 200, height: 15)
let deg45 = CGFloat(0.785398)
let degNeg45 = -deg45
let constraint = [SKConstraint.zRotation(SKRange(lowerLimit: degNeg45, upperLimit: deg45))]
paddle.constraints = constraint
addChild(paddle)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else { return }
guard let lastLocation = touches.first?.previousLocation(in: self) else { return }
guard location.y < self.frame.midY else { return }
// Our vertical plots:
let yVal = location.y
let lastY = lastLocation.y
// How much we moved in a certain direction this frame:
let deltaY = yVal - lastY
// This value represents 100% of a 45deg angle:
let oneHundredPercent = self.frame.height/2
assert(oneHundredPercent != 0)
// The % of 100%Val (45degrees) that we moved (in radians):
let absY = abs(deltaY)
let radToDegFactor = CGFloat(0.01745329252)
let multiplier = (absY / oneHundredPercent) * radToDegFactor
// I suggest a sensitivity of 2-4:
let sensitivity = CGFloat(3)
let amountToRotate = maximumRotation * (multiplier * sensitivity)
// Rotate the correct amount in the correct direction:
if deltaY > 0 {
// Rotate counter-clockwise:
paddle.run(.rotate(byAngle: amountToRotate, duration: 0))
} else {
// Rotate clockwise:
paddle.run(.rotate(byAngle: -amountToRotate, duration: 0))
}
}
}
只需打开一个新项目并尝试一下!
可能有更简单的方法来做到这一点,但这是我脑海中突然出现的方法。它也有点冗长,所以希望您可以逐步了解每个过程。
关于swift - 如何通过在屏幕的下半部分沿 y 轴移动手指来旋转彩色 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44472526/