Skip to content

Commit

Permalink
#85: Fixed bug when calculating a new speed that crosses speed 0, i.e…
Browse files Browse the repository at this point in the history
…. when the currentSpeed and targetSpeed have different signs.
  • Loading branch information
flemming-n-larsen committed Apr 28, 2024
1 parent 32f9f10 commit 4313857
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions server/src/main/kotlin/dev/robocode/tankroyale/server/rules/math.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dev.robocode.tankroyale.server.rules

import kotlin.math.abs
import kotlin.math.sign

/**
* Returns value clamped to the inclusive range of min and max.
Expand Down Expand Up @@ -30,20 +31,28 @@ fun calcNewBotSpeed(currentSpeed: Double, targetSpeed: Double): Double {
(currentSpeed - step).coerceAtLeast(MAX_BACKWARD_SPEED)
}
} else if (currentSpeed > 0) {
if (delta >= 0) {
val step = delta.coerceAtMost(ACCELERATION)
(currentSpeed + step).coerceAtMost(MAX_FORWARD_SPEED)
} else {
val step = delta.coerceAtLeast(DECELERATION)
(currentSpeed + step).coerceAtLeast(MAX_BACKWARD_SPEED)
if (currentSpeed.sign == targetSpeed.sign) {
if (delta >= 0) {
val step = delta.coerceAtMost(ACCELERATION)
(currentSpeed + step).coerceAtMost(MAX_FORWARD_SPEED)
} else {
val step = delta.coerceAtLeast(DECELERATION)
(currentSpeed + step).coerceAtLeast(MAX_BACKWARD_SPEED)
}
} else { // crossing the speed of 0
currentSpeed + (currentSpeed * ACCELERATION / DECELERATION) - ACCELERATION
}
} else { // currentSpeed < 0
if (delta >= 0) {
val step = (-delta).coerceAtLeast(DECELERATION)
(currentSpeed - step).coerceAtMost(-MAX_BACKWARD_SPEED)
} else {
val step = (-delta).coerceAtMost(ACCELERATION)
(currentSpeed - step).coerceAtLeast(-MAX_FORWARD_SPEED)
if (currentSpeed.sign == targetSpeed.sign) {
if (delta >= 0) {
val step = (-delta).coerceAtLeast(DECELERATION)
(currentSpeed - step).coerceAtMost(-MAX_BACKWARD_SPEED)
} else {
val step = (-delta).coerceAtMost(ACCELERATION)
(currentSpeed - step).coerceAtLeast(-MAX_FORWARD_SPEED)
}
} else { // crossing the speed of 0
currentSpeed + (currentSpeed * ACCELERATION / DECELERATION) + ACCELERATION
}
}
}
Expand Down Expand Up @@ -71,7 +80,8 @@ fun limitGunTurnRate(gunTurnRate: Double): Double = clamp(gunTurnRate, -MAX_GUN_
* @param radarTurnRate is the radar turn rate to limit
* @return limited radar turn rate.
*/
fun limitRadarTurnRate(radarTurnRate: Double): Double = clamp(radarTurnRate, -MAX_RADAR_TURN_RATE, MAX_RADAR_TURN_RATE)
fun limitRadarTurnRate(radarTurnRate: Double): Double =
clamp(radarTurnRate, -MAX_RADAR_TURN_RATE, MAX_RADAR_TURN_RATE)

/**
* Calculates the maximum driving turn rate for a specific speed.
Expand Down

0 comments on commit 4313857

Please sign in to comment.