Member-only story
Data-Oriented-Design — A Swift Introduction
Most developers know how to design software around maintainability and OOP. But what if performance matters more than encapsulation and access levels?
The problem
Think about a game where we have hundreds or even thousands of units moving at the same time. All these units would need a way to know when they should move, where they can move, and much more. All these units have some behaviour in common: movement.
Note: The code in this article is just for explanation. It lacks many things and is untested. It is mainly intended to showcase what an implementation can look like.
Our first step here is to define a structure that holds the movement. We call it Vector3
:
struct Vector3 {
// Convenience zero vector
static let zero = Vector3(x: 0, y: 0, z: 0)
var x: Float
var y: Float
var z: Float
init(x: Float, y: Float, z: Float) {
self.x = x
self.y = y
self.z = z
}
}
As a developer, this would be the perfect fit for a simple composition. So we define an interface.
protocol MoveUnit {
func move()
}