[英]Swift Compiler error: 'Double' is not convertible to CGFloat
I just began learning Swift. 我刚开始学习Swift。 I created a game project and a template came up.
我创建了一个游戏项目,并出现了一个模板。 I have not done anything to the code whatsoever.
我没有对代码做任何事情。 I tried to run the project but a compiler error popped up.
我试图运行该项目但是弹出了编译器错误。
I'm going off a tutorial so it could be something wrong with my environment or the book is already outdated. 我要去一个教程,所以它可能是我的环境有问题,或者这本书已经过时了。
Swift Compiler error: 'Double' is not convertible to CGFloat Swift编译错误:'Double'不能转换为CGFloat
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
let location = theEvent.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.position = location;
sprite.setScale(0.5)
let action = SKAction.rotateByAngle(M_PI, duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
The error occurs in let action = SKAction.rotateByAngle(M_PI, duration:1)
let action = SKAction.rotateByAngle(M_PI, duration:1)
发生错误
Here is a screenshot of the project settings 以下是项目设置的屏幕截图
You can convert it with CGFloat(M_PI)
. 您可以使用
CGFloat(M_PI)
进行转换。
For example the following code should work in your case (note the use of CGFloat
) 例如,以下代码应该适用于您的情况(请注意使用
CGFloat
)
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
You can declare pi like this in your code : let π = CGFloat(M_PI)
and then use let action = SKAction.rotateByAngle(π, duration:1)
您可以在代码中声明这样的pi:
let π = CGFloat(M_PI)
然后使用let action = SKAction.rotateByAngle(π, duration:1)
If you are going to use π a lot, it's way more simple. 如果你要使用π很多,那就更简单了。
You can type π with the shortcut alt+p 您可以使用快捷键alt + p键入π
The old M_PI was a Double, but the function did expect a CGFloat. 旧的M_PI是Double,但函数确实期望CGFloat。 A cast would be the solution.
演员阵容将成为解决方案。
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
With respect to Swift 5 it would be now: 关于Swift 5,它现在是:
let action = SKAction.rotate(byAngle: .pi, duration:1)
No need to cast anymore 不需要施放了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.