Patryk Piwowarczyk
Patryk Piwowarczyk

Reputation: 97

Swift 5, Idea for a function that would save the highest value

Hello fellow programmers.

Im building my little swift game and I stumbled upon a problem. I want my program to save the value of the highest Y coordinate that my ball ever acquired. So if a player went up and then down in 3d space, the Y value of the peak would be saved. And my question isn't about implementation but an idea of a function that could solve my problem. Keep in mind that coordinates update like 60 times per second and they aren't stored in any array or anything.

@edit And to add to it, its not as simple as caching the change of a vector, like when the velocity is 0 because the ball is moving diagonally.. so even when it starts falling the velocity still isnt 0 it just slows down..

let ball = ballNode.presentation
        let ballPosition = ball.position
        
        let targetPosition = SCNVector3(x: ballPosition.x, y: ballPosition.y, z:ballPosition)  //ball spawn point




Upvotes: 0

Views: 34

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236420

Just create a maxY property initialize it with zero.

var maxY: CGFloat = .zero

As suggested in comment by vadian compare the last value with the current one. You can also extend Comparable protocol and implement a mutating method:

extension Comparable {
    mutating func max(_ y: Self) {
        self = Swift.max(self, y)
    }
}

maxY.max(ballPosition.y)

Upvotes: 2

Related Questions