Reputation: 43
I am trying to add gravity and velocity to a player but can't fix this error. I've tried multiple different things but always get the same type of error. Could anyone tell what I am doing wrong and why its not possible to use multiply a CGPoint
and a CGFloat
or a CGFloat
* CGFloat
or a CGPoint
* a CGPoint
?
Upvotes: 2
Views: 1763
Reputation: 1
I noticed you're going through the "How to make a game like Flappy Bird" tutorial from Ray Wenderlich which includes some helper methods in files called SKUtils. When you add the SKUtils files from Ray Wenderlich, you may have to make sure they're checked in "Target Membership". Shouldn't have to, but I believe it depends on what you've got selected when you drag them into xcode. That is what's causing the error "Binary operator (*) cannot be applied to operands CGPoint and CGFloat" in this case. The other answers here will help you understand the problem, and learn to squash the bug yourself, but I'm assuming you just want the problem fixed, so you can continue the tutorial. Same would apply for many other cases where code and files are borrowed.
Upvotes: 0
Reputation: 416
Assuming you're working on iOS, suggest looking at the Core Motion apis like UIGravityBehavior, CMAcceleration, CGVector. Sorry I know this isn't directly answering your question, but hope that helps :)
This article seems to lay it out well: https://www.bignerdranch.com/blog/uidynamics-in-swift/
Generally though if you want to implement gravity directly you should be looking at vector math. And maybe using a helper lib such as https://github.com/nicklockwood/VectorMath (disclaimer: I'm not involved in this library, it's just an example)
Upvotes: 1
Reputation: 5241
Declare this extension
extension CGPoint {
static func * ( left : CGPoint , right : CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
static func * ( left : CGFloat , right : CGPoint) -> CGPoint {
return CGPoint(x: right.x * left, y: right.y * left)
}
}
Upvotes: 2
Reputation: 177
It is simply not possible to multiply a CGPoint with a Float. The first is a point and the second is a number. In real life, you can't multiply the coordinate where you're standing with a number. However what you can do, is to multiply each axis of the coordinate for itself and create a new point with the results.
I'm not sure what you're trying to do, but I'd simply change these lines to:
let gravityStep = CGPoint(x: 0, y: gravity * seconds)
let velocityStep = CGPoint(x: velocity.x * seconds, y: velocity.y * seconds)
This should work as expected.
Upvotes: 3
Reputation: 6369
You can use operator overloading to do this.
func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
}
Upvotes: 4