Last active
August 29, 2015 14:06
-
-
Save jarsen/1c73338641d50ad8ca60 to your computer and use it in GitHub Desktop.
Potential Fields in Swift
This file contains hidden or 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 | |
typealias Vector2D = (x: Float, y: Float) | |
typealias Point2D = Vector2D | |
func -(lhs: Vector2D, rhs: Vector2D) -> Vector2D { | |
return (lhs.x - rhs.x, lhs.y - rhs.y) | |
} | |
func length(vector: Vector2D) -> Float { | |
return sqrt(powf(vector.x, 2) + powf(vector.y, 2)) | |
} | |
func distance(#point1: Point2D, #point2: Point2D) -> Float { | |
return length(point1 - point2) | |
} | |
func attractiveField(agent: Point2D, goal: Point2D, scale α: Float, radius r: Float, spread s: Float) -> Vector2D { | |
let d = distance(point1: agent, point2: goal) | |
let θ = atan2(goal.y - agent.y, goal.x - agent.y) | |
if d < r { | |
return (0, 0) | |
} | |
else if r <= d && d <= s + r { | |
let Δx = α * (d - r) * cos(θ) | |
let Δy = α * (d - r) * sin(θ) | |
return (Δx, Δy) | |
} | |
else { // d > s + r | |
let Δx = α * s * cos(θ) | |
let Δy = α * s * sin(θ) | |
return (Δx, Δy) | |
} | |
} | |
func repulsiveField(agent: Point2D, obstacle: Point2D, scale β: Float, radius r: Float, spread s: Float) -> Vector2D { | |
let d = distance(point1: agent, point2: obstacle) | |
let θ = atan2(obstacle.y - agent.y, obstacle.x - agent.y) | |
if d < r { | |
let Δx = copysign(-cos(θ), Float.infinity) | |
let Δy = copysign(-sin(θ), Float.infinity) | |
return (Δx, Δy) | |
} | |
else if r <= d && d <= s + r { | |
let Δx = -β * (s + r - d) * cos(θ) | |
let Δy = -β * (s + r - d) * sin(θ) | |
return (Δx, Δy) | |
} | |
else { // d > s + r | |
return (0, 0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment