MassivePenguin
MassivePenguin

Reputation: 3711

Multiplying CGPoints using SKTUtils

I'm developing a Sprite Kit game using Swift, loosely following the Ray Wenderlich tutorials found here and here, and incorporating the SKTUtils module to allow easy addition/multiplication/division etc. of CGPoints.

The issue I'm finding is that all the online documentation refers to the older, Objective-C version of the module, while the code on Github has been rewritten to use Swift, and there's no accompanying usage guidelines.

The tutorial (written using Objective-C) states that the following code should work:

- (void)update:(NSTimeInterval)delta {
  CGPoint gravity = CGPointMake(0.0, -450.0);
  CGPoint gravityStep = CGPointMultiplyScalar(gravity, delta);
  self.velocity = CGPointAdd(self.velocity, gravityStep);
  CGPoint velocityStep = CGPointMultiplyScalar(self.velocity, delta);
  self.position = CGPointAdd(self.position, velocityStep);
}

Which, loosely translated to Swift, equates to:

func update(delta:NSTimeInterval) {
    let gravity:CGPoint = CGPointMake(0.0, -450.0);
    var gravityStep:CGPoint = CGPointMultiplyScalar(gravity * delta)
    self.velocity = self.velocity + gravityStep;
    let velocityStep:CGPoint = CGPointMultiplyScalar(self.velocity, delta)
    self.position = self.position + velocityStep;
}

However, the CGPointMultiplyScalar function has been changed to simply *. There's no accompanying documentation that I can find on how to implement thins, and my approaches aren't working:

func update(delta:NSTimeInterval) {
    ...
    var gravityStep:CGPoint = CGPoint(gravity * delta); // nope
    var gravityStep:CGPoint = gravity * delta; // nope
    ...
}

Does anyone out there have experience with this and can tell me where I'm going wrong?

Upvotes: 0

Views: 540

Answers (1)

Dániel Nagy
Dániel Nagy

Reputation: 12015

The CGPoint extension looks like:

public func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
    return CGPoint(x: point.x * scalar, y: point.y * scalar)
}

The scalar parameter needs a CGFloat, but you try to multiply it with an NSTimeInterval, and since there are no implicit conversions, you have to do

var gravityStep:CGPoint = gravity * CGFloat(delta)

to make it work.

Upvotes: 2

Related Questions