-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #20 from keith-gan/main
Add Grid
- Loading branch information
Showing
3 changed files
with
50 additions
and
9 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// | ||
// Grid.swift | ||
// TowerForge | ||
// | ||
// Created by Keith Gan on 22/3/24. | ||
// | ||
|
||
import SpriteKit | ||
|
||
class Grid: UnitSelectionNodeDelegate { | ||
let DEFAULT_NO_OF_ROWS = 8 | ||
|
||
private var entityManager: EntityManager | ||
private var noOfRows: Int | ||
|
||
init(entityManager: EntityManager) { | ||
self.entityManager = entityManager | ||
self.noOfRows = DEFAULT_NO_OF_ROWS | ||
} | ||
|
||
func unitSelectionNodeDidSpawn<T: BaseUnit & Spawnable>(ofType type: T.Type, position: CGPoint) { | ||
let snapPosition = CGPoint(x: position.x, y: snapYPosition(yPosition: position.y)) | ||
let unit = UnitGenerator.spawn(ofType: type, at: snapPosition, player: Player.ownPlayer, entityManager: entityManager) | ||
entityManager.add(unit) | ||
} | ||
|
||
private func snapYPosition(yPosition: Double) -> Double { | ||
let normalizedYPosition = normalizeYPosition(yPosition: yPosition) | ||
let screenHeight = Double(UIScreen.main.bounds.height) | ||
let rowHeight = screenHeight / Double(noOfRows) | ||
let rowIndex = Int(normalizedYPosition / rowHeight) | ||
let centerY = Double(rowIndex) * rowHeight + rowHeight / 2 | ||
return denormalizeYPosition(yPosition: centerY) | ||
} | ||
|
||
private func normalizeYPosition(yPosition: Double) -> Double { | ||
yPosition + UIScreen.main.bounds.height / 2 | ||
} | ||
|
||
private func denormalizeYPosition(yPosition: Double) -> Double { | ||
yPosition - UIScreen.main.bounds.height / 2 | ||
} | ||
} |