-
Notifications
You must be signed in to change notification settings - Fork 1
/
PhysicsSystem.swift
69 lines (54 loc) · 1.95 KB
/
PhysicsSystem.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//
// PhysicsSystem.swift
// star-dash
//
// Created by Ho Jun Hao on 13/3/24.
//
import Foundation
class PhysicsSystem: System {
var isActive: Bool
var dispatcher: EventModifiable?
var entityManager: EntityManager
init(_ entityManager: EntityManager, dispatcher: EventModifiable? = nil) {
self.isActive = true
self.dispatcher = dispatcher
self.entityManager = entityManager
}
func update(by deltaTime: TimeInterval) {
let physicsComponents = entityManager.componentMap.values.compactMap({ $0 as? PhysicsComponent })
for physicsComponent in physicsComponents {
physicsComponent.force = .zero
}
}
func isMoving(_ entityId: EntityId) -> Bool {
guard let physicsComponent = getPhysicsComponent(of: entityId) else {
return false
}
return physicsComponent.velocity != .zero
}
func isJumping(_ entityId: EntityId) -> Bool {
guard let physicsComponent = getPhysicsComponent(of: entityId) else {
return false
}
return physicsComponent.velocity.dy != .zero
}
func applyForce(to entityId: EntityId, newForce: CGVector) {
guard let physicsComponent = getPhysicsComponent(of: entityId) else {
return
}
let newForce = CGVector(dx: physicsComponent.force.dx + newForce.dx,
dy: physicsComponent.force.dy + newForce.dy)
physicsComponent.force = newForce
}
func sync(entityVelocityMap: [EntityId: CGVector]) {
for (entityId, newVelocity) in entityVelocityMap {
guard let physicsComponent = getPhysicsComponent(of: entityId) else {
continue
}
physicsComponent.velocity = newVelocity
}
}
private func getPhysicsComponent(of entityId: EntityId) -> PhysicsComponent? {
entityManager.component(ofType: PhysicsComponent.self, of: entityId)
}
}