From a3282098b1cad0cb51ac88fa640ce4838cb945b5 Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Mon, 21 Feb 2022 17:56:57 +0700 Subject: [PATCH] timer --- .../kotlin/ru/dbotthepony/kstarbound/Main.kt | 8 +++ .../ru/dbotthepony/kstarbound/world/World.kt | 64 +++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt index f6dd9e46..7101ad8f 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt @@ -137,6 +137,14 @@ fun main() { } } + for (i in 0 .. 10) { + client.world!!.timer(i * 1.0, 1) { + val projEnt = Projectile(client.world!!, Starbound.projectilesAccess["pill"]!!) + projEnt.position = Vector2d(i * 2.0 - 15.0, 13.0) + projEnt.spawn() + } + } + run { val stripes = 0 diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/world/World.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/world/World.kt index eef0eed3..1c7ab2d9 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/world/World.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/world/World.kt @@ -105,6 +105,40 @@ data class WorldSweepResult( private const val EPSILON = 0.00001 +class Timer(val period: Double, val executionTimes: Int, val func: (Timer) -> Unit) { + private var counter = 0.0 + var cycles = 0 + private set + var destroyed: Boolean = false + private set + + fun think(delta: Double) { + if (destroyed) { + throw IllegalStateException("This timer is destroyed") + } + + counter += delta + + if (counter >= period) { + counter -= period + func.invoke(this) + cycles++ + } + + if (!destroyed && executionTimes > 0 && cycles >= executionTimes) { + destroy() + } + } + + fun destroy() { + if (destroyed) { + throw IllegalStateException("Already destroyed") + } + + destroyed = true + } +} + abstract class World, ChunkType : Chunk>(val seed: Long = 0L) { protected val chunkMap = HashMap>() @@ -117,6 +151,14 @@ abstract class World, ChunkType : Chunk() + + fun timer(period: Double, executionTimes: Int, func: (Timer) -> Unit): Timer { + val timer = Timer(period, executionTimes, func) + timers.add(timer) + return timer + } + init { physics.contactFilter = object : IContactFilter { override fun shouldCollide(fixtureA: B2Fixture, fixtureB: B2Fixture): Boolean { @@ -220,6 +262,28 @@ abstract class World, ChunkType : Chunk