MeleeAttack .java

net.minecraft.world.entity.ai.behavior.MeleeAttack (class): members: create. imports: NearestVisibleLivingEntities, BehaviorBuilder, Mob, InteractionHand.

net.minecraft.world.entity.ai.behaviorclass49 linescommon1.8 KB

API Surface (2)

<T extends Mob> OneShot<T> create(final int cooldownBetweenAttacks)
<T extends Mob> OneShot<T> create(final Predicate<T> canAttackPredicate, final int cooldownBetweenAttacks)

Code Graph: Dependencies (7)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

MeleeAttack.java49 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.entity.ai.behavior;
2
3
import java.util.function.Predicate;
4
import net.minecraft.world.InteractionHand;
5
import net.minecraft.world.entity.LivingEntity;
6
import net.minecraft.world.entity.Mob;
7
import net.minecraft.world.entity.ai.behavior.declarative.BehaviorBuilder;
8
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
9
import net.minecraft.world.entity.ai.memory.NearestVisibleLivingEntities;
10
11
public class MeleeAttack {
12
	public static <T extends Mob> OneShot<T> create(final int cooldownBetweenAttacks) {
13
		return create(body -> true, cooldownBetweenAttacks);
14
	}
15
16
	public static <T extends Mob> OneShot<T> create(final Predicate<T> canAttackPredicate, final int cooldownBetweenAttacks) {
17
		return BehaviorBuilder.create(
18
			i -> i.group(
19
					i.registered(MemoryModuleType.LOOK_TARGET),
20
					i.present(MemoryModuleType.ATTACK_TARGET),
21
					i.absent(MemoryModuleType.ATTACK_COOLING_DOWN),
22
					i.present(MemoryModuleType.NEAREST_VISIBLE_LIVING_ENTITIES)
23
				)
24
				.apply(
25
					i,
26
					(lookTarget, attackTarget, attackCoolingDown, nearestEntities) -> (level, body, timestamp) -> {
27
						LivingEntity target = i.get(attackTarget);
28
						if (canAttackPredicate.test(body)
29
							&& !isHoldingUsableNonMeleeWeapon(body)
30
							&& body.isWithinMeleeAttackRange(target)
31
							&& i.<NearestVisibleLivingEntities>get(nearestEntities).contains(target)) {
32
							lookTarget.set(new EntityTracker(target, true));
33
							body.swingForAttack(InteractionHand.MAIN_HAND);
34
							body.doHurtTarget(level, target);
35
							attackCoolingDown.setWithExpiry(true, cooldownBetweenAttacks);
36
							return true;
37
						} else {
38
							return false;
39
						}
40
					}
41
				)
42
		);
43
	}
44
45
	private static boolean isHoldingUsableNonMeleeWeapon(final Mob body) {
46
		return body.isHolding(body::canUseNonMeleeWeapon);
47
	}
48
}
49

Decompiled Minecraft 26.3 source of MeleeAttack (net/minecraft/world/entity/ai/behavior/MeleeAttack.java) with Mojang official mappings, stored verbatim on the site.