Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 149
src/main/java/com/kodari/momentum/MomentumMod.java
package com.kodari.momentum;
import java.util.Map;
import java.util.WeakHashMap;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.entity.attribute.EntityAttributeInstance;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.server.network.ServerPlayerEntity;
public final class MomentumMod implements ModInitializer {
private static final double BASE_SPEED = 0.15;
private static final double ACCELERATION_PER_TICK = 0.005;
private static final double MAX_BASE_SPEED = 0.5;
private static final double MOVEMENT_EPSILON_SQUARED = 1.0E-8;
private static final int RESET_DELAY_TICKS = 100;
private static final Map<ServerPlayerEntity, MomentumState> PLAYER_STATES = new WeakHashMap<>();
@Override
public void onInitialize() {
ServerTickEvents.END_SERVER_TICK.register(server -> {
for (var player : server.getPlayerManager().getPlayerList()) {
double x = player.getX();
double z = player.getZ();
MomentumState state = PLAYER_STATES.get(player);
if (state == null) {
state = new MomentumState(x, z);
PLAYER_STATES.put(player, state);
} else if ((x - state.lastX) * (x - state.lastX) + (z - state.lastZ) * (z - state.lastZ) > MOVEMENT_EPSILON_SQUARED) {
state.speed = Math.min(MAX_BASE_SPEED, state.speed + ACCELERATION_PER_TICK);
state.stationaryTicks = 0;
} else if (state.stationaryTicks < RESET_DELAY_TICKS) {
state.stationaryTicks++;
if (state.stationaryTicks == RESET_DELAY_TICKS) {
state.speed = BASE_SPEED;
}
}
EntityAttributeInstance movementSpeed = player.getAttributeInstance(EntityAttributes.MOVEMENT_SPEED);
if (movementSpeed != null) {
movementSpeed.setBaseValue(state.speed);
}
state.lastX = x;
state.lastZ = z;
}
});
}
private static final class MomentumState {
private double lastX;
private double lastZ;
private double speed = BASE_SPEED;
private int stationaryTicks;
private MomentumState(double x, double z) {
this.lastX = x;
this.lastZ = z;
}
}
}