Skip to content

Commit

Permalink
Snap angles
Browse files Browse the repository at this point in the history
  • Loading branch information
agateau committed Jul 25, 2023
1 parent 90b4921 commit c845308
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions core-tests/src/com/agateau/utils/tests/AgcMathUtilsTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,11 @@ public void testLineDoesNotCrossSegment() {
assertThat(AgcMathUtils.lineCrossesSegment(l1, l2, s1, s2), is(false));
assertThat(AgcMathUtils.lineCrossesSegment(l1, l2, s2, s1), is(false));
}

@Test
public void testSnapAngle() {
assertThat(AgcMathUtils.snapAngle(92f), is(90f));
assertThat(AgcMathUtils.snapAngle(87f), is(90f));
assertThat(AgcMathUtils.snapAngle(183f), is(180f));
}
}
4 changes: 4 additions & 0 deletions core/src/com/agateau/pixelwheels/racer/VehicleRenderer.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.agateau.pixelwheels.gameobject.CellFrameBufferManager;
import com.agateau.pixelwheels.gameobject.CellFrameBufferUser;
import com.agateau.pixelwheels.utils.BodyRegionDrawer;
import com.agateau.utils.AgcMathUtils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
Expand Down Expand Up @@ -85,6 +86,9 @@ public void init(CellFrameBufferManager manager) {

private void drawBodyToCell(Batch batch, Body body, TextureRegion region) {
float angle = body.getAngle() * MathUtils.radiansToDegrees;
// Snap angles so that the vehicles do not slightly rotated when facing north, south, east
// or west. This is especially useful at startup.
angle = AgcMathUtils.snapAngle(angle);
float xOffset =
(body.getPosition().x - mVehicle.getPosition().x) / Constants.UNIT_FOR_PIXEL;
float yOffset =
Expand Down
9 changes: 9 additions & 0 deletions core/src/com/agateau/utils/AgcMathUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,13 @@ public static boolean rectangleContains(Rectangle rect, Vector2 position, float
}
return true;
}

public static float snapAngle(float value) {
value = normalizeAngle(value);
float snappedValue = MathUtils.round(value / 90f) * 90f;
if (Math.abs(snappedValue - value) < 2) {
return snappedValue;
}
return value;
}
}

0 comments on commit c845308

Please sign in to comment.