[英]How to move a UIImageView towards a certain point based on its degrees rotation?
我有一个火箭UIImageView,它使用 NSTimer 不断地围绕自身旋转:
rotationDegrees = rotationDegrees + 0.5
rocket.transform = CGAffineTransformMakeRotation(rotationDegrees * CGFloat(M_PI/180) )
一旦我点击屏幕,我需要它简单地将它发射到特定的轨迹中(我使用的是 UIKit,没有 SpriteKit,所以请不要提供 SpriteKit 建议:)以下是作为轨迹示例的图片:
我的 touchesBegan() 方法:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// Invalidate the timer that rotates the Rocket
rotationTimer.invalidate()
// Fire timer that moves the Rocket
moveRocketTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "moveRocket", userInfo: nil, repeats: true)
}
这是我需要像 8 点 X 和 8 点 Y 一样移动火箭的功能
func moveRocket() {
rocket.center.x = ??? + 8
rocket.center.y = ??? + 8
}
我正在使用 NSTimer 来移动火箭,因为我需要使用if CGRectIntersectsRect()检查它与另一个视图的碰撞
在此先感谢您的帮助!
您需要使用三角函数来计算给定角度的 x & y 变化:
y = sin(angle);
x = cos(angle);
这将为您提供范围从 -1 到 1 的值。您需要根据需要缩放它们(在您的问题中,您乘以 8。
您的角度值需要以弧度为单位。 因此,如果您的角度以度为单位,您可能需要编写一个函数来将度数转换为弧度:
func radiansFromDegrees(degrees: Float) -> Float
{
return degrees * M_PI/180;
}
如果你想让你的船移动 8 点/帧,那么你应该乘以 8。这样你就可以:
rocket.center.y += 8.0 * sin(radiansFromDegrees(angle));
rocket.center.x += 8.0 * cos(radiansFromDegrees(angle));
您可能需要进行一些类型转换才能使编译器满意,因为我认为 sin 和 cos 返回双精度值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.