Flappy Bird Coding Error in Swift

試著忘記壹切 提交于 2019-12-13 08:05:03

问题


I've encountered a coding error for my flappy bird project, in Xcode 6.1.

The code is to allow rotation of the bird, and it reads:

bird.zRotation = self.acotarMinMax(-1, max: 0.3, valor: bird.physicsBody?.velocity.dy * (bird.physicsBody?.velocity.dy < 0 ? 0.003 : 0.001))

the error occurs under dy, it reads:

value of optional type 'CGFloat?' not unwrapped; did you mean to use '!' or '?'?

How can I correct the error, or is there another way to generate rotation?

I am a total beginner of Swift, so I'm having a hard time figuring out if this is a syntax problem or something to do with the updated version.

I obtained the code from a online tutorial, and it worked in the video.


回答1:


Read up on the Swift Optional class: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

So it seems that dy is an Optional value, which means that it either has a value or it does not, but you don't know until you look into it (like Schroedinger's Cat). So if you need this value and you know it will not be nil, you unwrap it by writing bird.physicsBody?.velocity.dy! which will look into the "box" and take the value out but crash if there is nothing inside. If you write dy? it will look into the box but ignore it if the box is empty.

More on Optional Chaining (which is what you do) here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html




回答2:


So I just figured out my error.

As Sebastian correctly pointed out, it is to do with optional chaining.

The code that worked is:

bird.zRotation = self.acotarMinMax(-1, max: 1, valor: bird.physicsBody!.velocity.dy * (bird.physicsBody!.velocity.dy < 0 ? 0.002 : 0.002))

I used '!' to force a value on physicsBody. The precise mechanism of why this works is still a blur to me. But my guess is to do with the new version's correction method.



来源:https://stackoverflow.com/questions/26752831/flappy-bird-coding-error-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!