Give iron and snow golems their behaviour

Iron golems hunt monsters (not creepers), close in, swing for a random
half to one and a half times their damage and throw the target up, show
cracks as they weaken, take iron ingots for repairs, offer poppies to
villagers and hold a grudge against a player who hits them. Snow golems
pelt monsters with snowballs, leave a snow trail and melt in hot biomes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 06:44:57 +02:00
parent 459db087d6
commit 71f6d80613
7 changed files with 360 additions and 0 deletions
@@ -360,6 +360,8 @@ impl Game<'_> {
thundering: thunder > 0.9,
nether: self.dim == Dim::Nether,
block_tags: &self.res.items.block_tags,
biomes: &self.res.biomes,
mob_griefing: self.ui.rules.bool("mob_griefing"),
}
}
/// NaturalSpawner.spawnForChunk over the chunks within 8 of the player.
@@ -685,6 +687,23 @@ impl Game<'_> {
}
}
}
MobEvent::Launch { target, up } => match target {
Who::Player => {
if let Some(p) = self.player.as_mut() {
p.velocity.y += up;
}
}
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.velocity.y += up;
}
}
},
MobEvent::HurtSelf { mob, kind, amount } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.damage(amount, horizon_client::mobs::Damage::of(kind));
}
}
MobEvent::SetTarget { mob, target } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.ai.target = Some(target);
@@ -1562,6 +1581,14 @@ impl Game<'_> {
m.position.z.floor() as i32 >> 4,
));
}
// IronGolem.mobInteract: an iron ingot repairs 25 health.
Species::IronGolem
if item == "minecraft:iron_ingot" && m.health < m.attrs.max_health =>
{
m.health = (m.health + 25.0).min(m.attrs.max_health);
consume = true;
sound = Some("entity.iron_golem.repair");
}
Species::Creeper if item == "minecraft:flint_and_steel" => {
m.extra.flag = true;
sound = Some("item.flintandsteel.use");
+15
View File
@@ -14,6 +14,7 @@ pub mod data;
pub mod enderman;
pub mod farm;
pub mod goals;
pub mod golem;
pub mod hostile;
pub mod keyframes;
pub mod living;
@@ -566,6 +567,17 @@ pub enum MobEvent {
name: &'static str,
effect: bool,
},
/// Throw an entity upward (iron golem swings).
Launch {
target: Who,
up: f64,
},
/// Damage the mob itself (snow golems melting).
HurtSelf {
mob: u32,
kind: DamageKind,
amount: f32,
},
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
GiftLoot {
table: &'static str,
@@ -634,6 +646,9 @@ pub struct MobWorld<'a> {
pub thundering: bool,
pub nether: bool,
pub block_tags: &'a HashMap<String, std::collections::HashSet<String>>,
pub biomes: &'a crate::biome::Biomes,
/// The `mob_griefing` game rule.
pub mob_griefing: bool,
}
impl Mob {
pub fn new(id: u32, kind: Arc<MobType>, position: Vec3, yaw: f32) -> Self {
+13
View File
@@ -72,6 +72,7 @@ pub enum Family {
Tame,
/// Blazes and ghasts.
Nether,
Golem,
/// Slimes and magma cubes.
Cube,
}
@@ -101,6 +102,7 @@ pub fn family(s: Species) -> Family {
S::Witch => Family::Witch,
S::Wolf | S::Cat => Family::Tame,
S::Blaze | S::Ghast => Family::Nether,
S::IronGolem | S::SnowGolem => Family::Golem,
S::Enderman => Family::Enderman,
S::Slime | S::MagmaCube => Family::Cube,
_ => Family::Generic,
@@ -119,6 +121,8 @@ pub fn register(m: &mut Mob) {
Family::Tame => super::tame::register(m),
Family::Nether if m.species() == Species::Ghast => super::nether::register_ghast(m),
Family::Nether => super::nether::register_blaze(m),
Family::Golem if m.species() == Species::IronGolem => super::golem::register_iron(m),
Family::Golem => super::golem::register_snow(m),
Family::Enderman => super::enderman::register(m),
Family::Cube => super::cube::register(m),
}
@@ -474,6 +478,8 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Wolf => super::tame::ai_step(m, w, events),
Species::Cat => super::tame::cat_ai_step(m, events),
Species::Blaze => super::nether::blaze_ai_step(m, events),
Species::IronGolem => super::golem::iron_ai_step(m),
Species::SnowGolem => super::golem::snow_ai_step(m, w, events),
Species::Slime | Species::MagmaCube => super::cube::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => {
@@ -577,11 +583,18 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
match m.species() {
Species::Enderman => super::enderman::after_hurt(m, source),
Species::Wolf => super::tame::after_hurt(m, source),
// NeutralMob: an iron golem hit by the player stays angry a while.
Species::IronGolem if source.attacker == Some(Who::Player) => {
m.extra.anger = 400 + m.random.next_int_bound(380).unwrap_or(0);
}
_ => {}
}
}
/// Mob.doHurtTarget: attack damage (+ species extras) to the target.
pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if m.species() == Species::IronGolem {
return super::golem::iron_hurt_target(m, who, cx);
}
let mut amount = m.attrs.attack_damage;
let from = [m.position.x, m.position.y, m.position.z];
let source = Damage::mob(m.id, from);
+1
View File
@@ -419,6 +419,7 @@ pub fn setup(
}
Anim::Witch => super::witch::anim(m, s, p),
Anim::Wolf => super::tame::anim(m, s, p),
Anim::IronGolem => super::golem::iron_anim(m, s, p),
Anim::Blaze => super::nether::blaze_anim(s, p),
Anim::Ghast => super::nether::ghast_anim(s, p),
Anim::Feline if m.species() == super::Species::Cat => super::tame::cat_anim(m, s, p),
+291
View File
@@ -0,0 +1,291 @@
//! Golems: iron golems (fighting monsters, the heavy swing that throws its
//! target up, cracks as they weaken, iron repairs and poppies for villagers)
//! and snow golems (snowballs at monsters, the snow trail, melting).
use super::{
Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{
Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, Prey,
RandomLookAround, Stroll, goal_clone,
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `Enemy` monsters an iron golem goes after (never creepers).
fn golem_prey(s: &super::Seen) -> bool {
s.hostile && s.species != Species::Creeper
}
pub fn register_iron(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(1, MeleeAttack::new(1.0, true));
g.add(
2,
MoveTowardsTarget {
speed: 0.9,
within: 32.0,
},
);
g.add(4, Stroll::avoiding_water(0.6));
g.add(
5,
OfferFlower {
ticks: 0,
villager: None,
},
);
g.add(7, LookAtPlayer::new(6.0));
g.add(8, RandomLookAround::default());
m.ai.targets.add(2, HurtByTarget::new());
m.ai.targets.add(
3,
NearestTarget::player(true)
.interval(10)
.when(|m, _| m.extra.anger > 0),
);
m.ai.targets.add(
3,
NearestTarget::new(Prey::Filter(golem_prey), false).interval(5),
);
}
/// `MoveTowardsTargetGoal`: close in on a target within range.
#[derive(Clone, Debug)]
struct MoveTowardsTarget {
speed: f64,
within: f64,
}
impl Goal for MoveTowardsTarget {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(t) = m.ai.target.and_then(|t| cx.w.target_info(t)) else {
return false;
};
if m.distance_sqr(t.position) > self.within * self.within {
return false;
}
m.nav_move_to_entity(
cx.w,
[t.position.x, t.position.y, t.position.z],
0,
self.speed,
)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
!m.ai.nav.is_done()
&& m.ai
.target
.and_then(|t| cx.w.target_info(t))
.is_some_and(|t| t.alive && m.distance_sqr(t.position) < self.within * self.within)
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.nav_stop();
}
}
/// `OfferFlowerGoal`: by day, now and then, hold out a poppy to a villager.
#[derive(Clone, Debug)]
struct OfferFlower {
ticks: i32,
villager: Option<u32>,
}
impl Goal for OfferFlower {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !cx.w.daylight || m.random.next_int_bound(8000).unwrap_or(1) != 0 {
return false;
}
self.villager =
cx.w.nearby(m.position, 6.0, |s| {
s.species == Species::Villager && s.alive
})
.map(|s| s.id)
.next();
self.villager.is_some()
}
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
self.ticks > 0
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
self.ticks = 400;
m.extra.counter = 400;
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.extra.counter = 0;
self.villager = None;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(v) = self.villager.and_then(|v| cx.w.seen(v)) {
m.look_at_speed([v.position.x, v.eye_y, v.position.z], 30.0, 30.0);
}
self.ticks -= 1;
}
}
/// `IronGolem.doHurtTarget`: half to one and a half times the damage, and
/// the target is thrown upward.
pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
m.extra.anim_ticks = 10;
let attack = m.attrs.attack_damage;
let amount = if attack as i32 > 0 {
attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32
} else {
attack
};
let from = [m.position.x, m.position.y, m.position.z];
match who {
Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)),
Who::Mob(id) => cx.events.push(MobEvent::AttackMob {
target: id,
amount,
source: super::Damage::mob(m.id, from),
}),
}
cx.events.push(MobEvent::Launch {
target: who,
up: 0.4,
});
cx.events.push(MobEvent::Sound(
"entity.iron_golem.attack",
m.center(),
1.0,
1.0,
));
}
/// `IronGolem.aiStep` timers and anger.
pub fn iron_ai_step(m: &mut Mob) {
if m.extra.anim_ticks > 0 {
m.extra.anim_ticks -= 1;
}
if m.extra.counter > 0 {
m.extra.counter -= 1;
}
if m.extra.anger > 0 {
m.extra.anger -= 1;
if m.extra.anger == 0 && m.ai.target == Some(Who::Player) {
m.ai.target = None;
}
}
}
/// `Crackiness.GOLEM` texture for the health left.
pub fn crackiness(m: &Mob) -> Option<&'static str> {
let f = m.health / m.attrs.max_health;
if f < 0.25 {
Some("entity/iron_golem/iron_golem_crackiness_high")
} else if f < 0.5 {
Some("entity/iron_golem/iron_golem_crackiness_medium")
} else if f < 0.75 {
Some("entity/iron_golem/iron_golem_crackiness_low")
} else {
None
}
}
fn triangle_wave(x: f32, period: f32) -> f32 {
((x % period) - period * 0.5).abs() / (period * 0.5) * 2.0 - 1.0
}
/// `IronGolemModel.setupAnim`.
pub fn iron_anim(m: &Mob, s: &State, p: &mut Poses) {
let attack = if m.extra.anim_ticks > 0 {
m.extra.anim_ticks as f32 - s.partial
} else {
0.0
};
let (pos, speed) = (s.pos, s.speed);
if attack > 0.0 {
p.xrot("right_arm", -2.0 + 1.5 * triangle_wave(attack, 10.0));
p.xrot("left_arm", -2.0 + 1.5 * triangle_wave(attack, 10.0));
} else if m.extra.counter > 0 {
p.xrot(
"right_arm",
-0.8 + 0.025 * triangle_wave(m.extra.counter as f32, 70.0),
);
p.xrot("left_arm", 0.0);
} else {
p.xrot("right_arm", (-0.2 + 1.5 * triangle_wave(pos, 13.0)) * speed);
p.xrot("left_arm", (-0.2 - 1.5 * triangle_wave(pos, 13.0)) * speed);
}
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
p.xrot("right_leg", -1.5 * triangle_wave(pos, 13.0) * speed);
p.xrot("left_leg", 1.5 * triangle_wave(pos, 13.0) * speed);
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
}
pub fn register_snow(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(
1,
super::witch::RangedAttack::new(1.25, 20, 20, 10.0, snowball_attack),
);
g.add(2, Stroll::avoiding_water(1.0));
g.add(3, LookAtPlayer::new(6.0));
g.add(4, RandomLookAround::default());
m.ai.targets.add(
1,
NearestTarget::new(Prey::Filter(|s| s.hostile), true).interval(10),
);
}
/// `SnowGolem.performRangedAttack`.
fn snowball_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
let Some(t) = cx.w.target_info(who) else {
return;
};
let start = Vec3::new(m.position.x, m.eye_y() - 0.1, m.position.z);
let xd = t.position.x - m.position.x;
let yd = t.eye_y - 1.1;
let zd = t.position.z - m.position.z;
let yo = (xd * xd + zd * zd).sqrt() * 0.2;
let mut p = Projectile::new(ProjectileKind::Snowball, start, Some(Who::Mob(m.id)));
// rangedAttackUncertainty: 14 - 4 * difficulty (normal: 6).
p.shoot(&mut m.random, [xd, yd + yo - start.y, zd], 1.6, 6.0);
cx.events.push(MobEvent::Projectile(p));
let pitch = 0.4 / (m.random.next_float() * 0.4 + 0.8);
cx.events.push(MobEvent::Sound(
"entity.snow_golem.shoot",
m.center(),
1.0,
pitch,
));
}
/// `SnowGolem.aiStep`: melting in hot biomes, the snow trail.
pub fn snow_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
// EnvironmentAttributes.SNOW_GOLEM_MELTS: the hot biomes and the Nether.
if w.nether || w.temperature(x, y, z) > 1.0 {
events.push(MobEvent::HurtSelf {
mob: m.id,
kind: super::DamageKind::OnFire,
amount: 1.0,
});
}
if !w.mob_griefing {
return;
}
for i in 0..4 {
let xx = (m.position.x + f64::from((i % 2 * 2 - 1) as f32 * 0.25)).floor() as i32;
let zz = (m.position.z + f64::from((i / 2 % 2 * 2 - 1) as f32 * 0.25)).floor() as i32;
let here = w.facts.get(w.world.block(xx, y, zz));
let below = w.facts.get(w.world.block(xx, y - 1, zz));
// SnowLayerBlock.canSurvive: a full top face, not ice.
let ice = matches!(
below.name.as_ref(),
"minecraft:ice" | "minecraft:packed_ice" | "minecraft:barrier"
);
if here.name.as_ref() == "minecraft:air" && below.full_collision && !ice {
events.push(MobEvent::SetBlockName {
pos: [xx, y, zz],
name: "minecraft:snow",
effect: false,
});
}
}
let _ = z;
}
+6
View File
@@ -301,6 +301,12 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
false,
);
}
// IronGolemCrackinessLayer.
S::IronGolem => {
if let Some(texture) = super::golem::crackiness(m) {
push(&mut v, "iron_golem#main", texture, white, false);
}
}
// SlimeOuterLayer: the translucent outer cube.
S::Slime => push(&mut v, "slime#outer", "entity/slime/slime", white, false),
S::Sheep if !m.extra.sheared => {
+7
View File
@@ -19,6 +19,13 @@ pub struct TargetInfo {
pub creative: bool,
}
impl MobWorld<'_> {
/// The biome's base temperature at a position.
pub fn temperature(&self, x: i32, y: i32, z: i32) -> f32 {
self.world
.chunks
.get(&(x >> 4, z >> 4))
.map_or(0.8, |c| self.biomes.get(c.biome(x, y, z)).temperature)
}
/// `Heightmap.Types.MOTION_BLOCKING`: above the highest blocking block.
pub fn motion_blocking_height(&self, x: i32, z: i32) -> i32 {
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;