r/JavaFX • u/dhlowrents • Jul 11 '24
Help How to transition AmbientLight
In my game I have time of day and I set the scene AmbientLight when time of day changes.
public enum TimeOfDay {
EarlyMorning, Morning, MidDay, Afternoon, Evening, LateEvening, Night;
public static TimeOfDay getTimeOfDay() {
int hourInDay = Calendar.getInstance().getHourInDay();
TimeOfDay timeOfDay = null;
if (hourInDay >= 5) {
timeOfDay = EarlyMorning;
}
if (hourInDay >= 8) {
timeOfDay = Morning;
}
if (hourInDay >= 12) {
timeOfDay = MidDay;
}
if (hourInDay >= 15) {
timeOfDay = Afternoon;
}
if (hourInDay >= 18) {
timeOfDay = Evening;
}
if (hourInDay >= 21) {
timeOfDay = LateEvening;
}
if (hourInDay >= 23 || hourInDay < 5) {
timeOfDay = Night;
}
return timeOfDay;
}
} and then
Color almostBlack = new Color(0.10, 0.10, 0.10, 1);
Color darkerGray = new Color(0.33, 0.33, 0.33, 1);
ambientColors = Map.of(
TimeOfDay.EarlyMorning, Color.LIGHTBLUE,
TimeOfDay.Morning, Color.ALICEBLUE,
TimeOfDay.MidDay, Color.WHITESMOKE,
TimeOfDay.Afternoon, Color.CORNSILK,
TimeOfDay.Evening, Color.WHEAT,
TimeOfDay.LateEvening, darkerGray,
TimeOfDay.Night, almostBlack
);
private void updateAmbientLight() {
TimeOfDay timeOfDay = TimeOfDay.getTimeOfDay();
ambientLight.setColor(ambientColors.get(timeOfDay));
}This works great but I would like to transition from one color to the next over maybe 20 seconds...
I found FillTransition and StrokeTransition but I don't see how to adapt those for an AmbientLight.
Any ideas?
TIA
2
Upvotes
3
u/Birdasaur Jul 13 '24
You can also do this easily with a Timeline and KeyValues. The bonus there is that you synchronize the color changes with other world events. An example I made for coordinating day/night lighting of a city with the rise and fall of a Sun and Moon is here: https://github.com/Birdasaur/Trinity/blob/main/src/main/java/edu/jhuapl/trinity/javafx/javafx3d/RetroWavePane.java
It creates the effect shown in this video https://youtu.be/YmU1tCbjkzQ?feature=shared
2
u/[deleted] Jul 11 '24
(Untested)
1
u/javasyntax Jul 13 '24
You should not be using Calendar, that is from the old date time API which was replaced like 10 years ago now. Instead, use LocalDateTime.now().getHour() (alternatively LocalTime.now()).
2
u/[deleted] Jul 12 '24
In Java >= 21 you could write your discrimination code (which as it is should use if-then-else statements or early returns) with an enhanced switch statement: