Last active
February 14, 2017 15:12
-
-
Save krooked/5f0457b9e64a540b2701bd8f046a760f to your computer and use it in GitHub Desktop.
Runge Kutta 2nd order movement test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
import PlaygroundSupport | |
// Helper functions | |
func * (point: CGPoint, scalar: CGFloat) -> CGPoint { | |
return CGPoint(x: point.x * scalar, y: point.y * scalar) | |
} | |
func + (left: CGPoint, right: CGPoint) -> CGPoint { | |
return CGPoint(x: left.x + right.x, y: left.y + right.y) | |
} | |
func / (point: CGPoint, scalar: CGFloat) -> CGPoint { | |
return CGPoint(x: point.x / scalar, y: point.y / scalar) | |
} | |
// Variables | |
var timerCount = 0 | |
let maxTimeCount = 10 | |
let framerate = 1.0 | |
var position = CGPoint(x: 0, y: 0) | |
var velocity = CGPoint(x: 0, y: 0) | |
var acceleration = CGPoint(x: 10, y: 0) | |
let mass = 1 | |
func force(position: CGPoint, velocity: CGPoint, time: CGFloat = 0) -> CGPoint { | |
return acceleration | |
} | |
// Update function | |
func update(deltaTime: Double) { | |
let acceleration1 = force(position: position, velocity: velocity) | |
let position2 = position + velocity * CGFloat(deltaTime) | |
let velocity2 = velocity + acceleration1 * CGFloat(deltaTime) | |
let acceleration2 = force(position: position2, velocity: velocity2) | |
position = position + (velocity + velocity2) / 2 * CGFloat(deltaTime) | |
velocity = velocity + (acceleration1 + acceleration2) / 2 * CGFloat(deltaTime) | |
} | |
// Run update function | |
while (timerCount < maxTimeCount) { | |
timerCount += 1 | |
update(deltaTime: 1.0.divided(by: framerate)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment