CrossbowItem .java

net.minecraft.world.item.CrossbowItem (class): members: MAX_CHARGE_DURATION, START_SOUND_PERCENT, midLoadSoundPlayed, MID_SOUND_PERCENT, getChargeDuration.

net.minecraft.world.itemclass305 linescommonextends ProjectileWeaponItem11.4 KB

API Surface (17)

Predicate<ItemStack> getSupportedHeldProjectiles()
Predicate<ItemStack> getAllSupportedProjectiles()
InteractionResult use(final Level level, final Player player, final InteractionHand hand)
boolean releaseUsing(final ItemStack itemStack, final Level level, final LivingEntity entity, final int remainingTime)
boolean isCharged(final ItemStack itemStack)
void shootProjectile(final LivingEntity livingEntity, final Projectile projectileEntity, final int index, final float power, final float uncertainty, final float angle, final @Nullable LivingEntity targetOverride)
Projectile createProjectile(final Level level, final LivingEntity shooter, final ItemStack heldItem, final ItemStack projectile, final boolean isCrit)
int getDurabilityUse(final ItemStack projectile)
void performShooting(final Level level, final LivingEntity shooter, final InteractionHand hand, final ItemStack weapon, final float power, final float uncertainty, final @Nullable LivingEntity targetOverride)
void onUseTick(final Level level, final LivingEntity entity, final ItemStack itemStack, final int ticksRemaining)
int getUseDuration(final ItemStack itemStack, final LivingEntity user)
int getChargeDuration(final ItemStack crossbow, final LivingEntity user)
ItemUseAnimation getUseAnimation(final ItemStack itemStack)
boolean useOnRelease(final ItemStack itemStack)
int getDefaultProjectileRange()
String getSerializedName()
record ChargingSounds(Optional<Holder<SoundEvent>> start, Optional<Holder<SoundEvent>> mid, Optional<Holder<SoundEvent>> end)

Fields & Constants (21)

MAX_CHARGE_DURATION
DEFAULT_RANGE
START_SOUND_PERCENT
MID_SOUND_PERCENT
ARROW_POWER
FIREWORK_POWER
MOB_ARROW_POWER
DEFAULT_SOUNDS
startSoundPlayed
midLoadSoundPlayed
livingEntity
projectileEntity
index
power
uncertainty
angle
projectile
level
shooter
hand
weapon

String literals (4)

"none"
"arrow"
"rocket"
"start"

Full Source

CrossbowItem.java305 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.item;
2
3
import com.mojang.serialization.Codec;
4
import com.mojang.serialization.codecs.RecordCodecBuilder;
5
import java.util.List;
6
import java.util.Optional;
7
import java.util.function.Predicate;
8
import net.minecraft.advancements.triggers.CriteriaTriggers;
9
import net.minecraft.core.Holder;
10
import net.minecraft.core.component.DataComponents;
11
import net.minecraft.server.level.ServerLevel;
12
import net.minecraft.server.level.ServerPlayer;
13
import net.minecraft.sounds.SoundEvent;
14
import net.minecraft.sounds.SoundEvents;
15
import net.minecraft.sounds.SoundSource;
16
import net.minecraft.stats.Stats;
17
import net.minecraft.util.Mth;
18
import net.minecraft.util.RandomSource;
19
import net.minecraft.util.StringRepresentable;
20
import net.minecraft.world.InteractionHand;
21
import net.minecraft.world.InteractionResult;
22
import net.minecraft.world.entity.LivingEntity;
23
import net.minecraft.world.entity.player.Player;
24
import net.minecraft.world.entity.projectile.FireworkRocketEntity;
25
import net.minecraft.world.entity.projectile.Projectile;
26
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
27
import net.minecraft.world.item.component.ChargedProjectiles;
28
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
29
import net.minecraft.world.item.enchantment.EnchantmentHelper;
30
import net.minecraft.world.level.Level;
31
import net.minecraft.world.phys.Vec3;
32
import org.joml.Quaternionf;
33
import org.joml.Vector3f;
34
import org.jspecify.annotations.Nullable;
35
36
public class CrossbowItem extends ProjectileWeaponItem {
37
	private static final float MAX_CHARGE_DURATION = 1.25F;
38
	public static final int DEFAULT_RANGE = 8;
39
	private boolean startSoundPlayed = false;
40
	private boolean midLoadSoundPlayed = false;
41
	private static final float START_SOUND_PERCENT = 0.2F;
42
	private static final float MID_SOUND_PERCENT = 0.5F;
43
	private static final float ARROW_POWER = 3.15F;
44
	private static final float FIREWORK_POWER = 1.6F;
45
	public static final float MOB_ARROW_POWER = 1.6F;
46
	private static final CrossbowItem.ChargingSounds DEFAULT_SOUNDS = new CrossbowItem.ChargingSounds(
47
		Optional.of(SoundEvents.CROSSBOW_LOADING_START), Optional.of(SoundEvents.CROSSBOW_LOADING_MIDDLE), Optional.of(SoundEvents.CROSSBOW_LOADING_END)
48
	);
49
50
	public CrossbowItem(final Item.Properties properties) {
51
		super(properties);
52
	}
53
54
	@Override
55
	public Predicate<ItemStack> getSupportedHeldProjectiles() {
56
		return ARROW_OR_FIREWORK;
57
	}
58
59
	@Override
60
	public Predicate<ItemStack> getAllSupportedProjectiles() {
61
		return ARROW_ONLY;
62
	}
63
64
	@Override
65
	public InteractionResult use(final Level level, final Player player, final InteractionHand hand) {
66
		ItemStack itemStack = player.getItemInHand(hand);
67
		ChargedProjectiles chargedProjectiles = itemStack.get(DataComponents.CHARGED_PROJECTILES);
68
		if (chargedProjectiles != null && !chargedProjectiles.isEmpty()) {
69
			this.performShooting(level, player, hand, itemStack, getShootingPower(chargedProjectiles), 1.0F, null);
70
			return InteractionResult.CONSUME;
71
		} else if (!player.getProjectile(itemStack).isEmpty()) {
72
			this.startSoundPlayed = false;
73
			this.midLoadSoundPlayed = false;
74
			player.startUsingItem(hand);
75
			return InteractionResult.CONSUME;
76
		} else {
77
			return InteractionResult.FAIL;
78
		}
79
	}
80
81
	private static float getShootingPower(final ChargedProjectiles projectiles) {
82
		return projectiles.contains(Items.FIREWORK_ROCKET) ? 1.6F : 3.15F;
83
	}
84
85
	@Override
86
	public boolean releaseUsing(final ItemStack itemStack, final Level level, final LivingEntity entity, final int remainingTime) {
87
		int timeHeld = this.getUseDuration(itemStack, entity) - remainingTime;
88
		return getPowerForTime(timeHeld, itemStack, entity) >= 1.0F && isCharged(itemStack);
89
	}
90
91
	private static boolean tryLoadProjectiles(final LivingEntity shooter, final ItemStack heldItem) {
92
		List<ItemStack> drawn = draw(heldItem, shooter.getProjectile(heldItem), shooter);
93
		if (!drawn.isEmpty()) {
94
			heldItem.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.ofNonEmpty(drawn));
95
			return true;
96
		} else {
97
			return false;
98
		}
99
	}
100
101
	public static boolean isCharged(final ItemStack itemStack) {
102
		ChargedProjectiles projectiles = itemStack.getOrDefault(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY);
103
		return !projectiles.isEmpty();
104
	}
105
106
	@Override
107
	protected void shootProjectile(
108
		final LivingEntity livingEntity,
109
		final Projectile projectileEntity,
110
		final int index,
111
		final float power,
112
		final float uncertainty,
113
		final float angle,
114
		final @Nullable LivingEntity targetOverride
115
	) {
116
		Vector3f shotVector;
117
		if (targetOverride != null) {
118
			double xd = targetOverride.getX() - livingEntity.getX();
119
			double zd = targetOverride.getZ() - livingEntity.getZ();
120
			double distanceToTarget = Math.sqrt(xd * xd + zd * zd);
121
			double yd = targetOverride.getY(0.3333333333333333) - projectileEntity.getY() + distanceToTarget * 0.2F;
122
			shotVector = getProjectileShotVector(livingEntity, new Vec3(xd, yd, zd), angle);
123
		} else {
124
			Vec3 upVector = livingEntity.getUpVector(1.0F);
125
			Quaternionf upQuaternion = new Quaternionf().setAngleAxis(angle * (float) (Math.PI / 180.0), upVector.x, upVector.y, upVector.z);
126
			Vec3 viewVec = livingEntity.getViewVector(1.0F);
127
			shotVector = viewVec.toVector3f().rotate(upQuaternion);
128
		}
129
130
		projectileEntity.shoot(shotVector.x(), shotVector.y(), shotVector.z(), power, uncertainty);
131
		float soundPitch = getShotPitch(livingEntity.getRandom(), index);
132
		livingEntity.level()
133
			.playSound(null, livingEntity.getX(), livingEntity.getY(), livingEntity.getZ(), SoundEvents.CROSSBOW_SHOOT, livingEntity.getSoundSource(), 1.0F, soundPitch);
134
	}
135
136
	private static Vector3f getProjectileShotVector(final LivingEntity body, final Vec3 originalVector, final float angle) {
137
		Vector3f viewVec = originalVector.toVector3f().normalize();
138
		Vector3f rightVectorPreRot = new Vector3f(viewVec).cross(new Vector3f(0.0F, 1.0F, 0.0F));
139
		if (rightVectorPreRot.lengthSquared() <= 1.0E-7) {
140
			Vec3 up = body.getUpVector(1.0F);
141
			rightVectorPreRot = new Vector3f(viewVec).cross(up.toVector3f());
142
		}
143
144
		Vector3f viewVec3f = new Vector3f(viewVec).rotateAxis((float) (Math.PI / 2), rightVectorPreRot.x, rightVectorPreRot.y, rightVectorPreRot.z);
145
		return new Vector3f(viewVec).rotateAxis(angle * (float) (Math.PI / 180.0), viewVec3f.x, viewVec3f.y, viewVec3f.z);
146
	}
147
148
	@Override
149
	protected Projectile createProjectile(
150
		final Level level, final LivingEntity shooter, final ItemStack heldItem, final ItemStack projectile, final boolean isCrit
151
	) {
152
		if (projectile.is(Items.FIREWORK_ROCKET)) {
153
			return new FireworkRocketEntity(level, projectile, shooter, shooter.getX(), shooter.getEyeY() - 0.15F, shooter.getZ(), true);
154
		}
155
156
		Projectile projectileEntity = super.createProjectile(level, shooter, heldItem, projectile, isCrit);
157
		if (projectileEntity instanceof AbstractArrow arrow) {
158
			arrow.setSoundEvent(SoundEvents.CROSSBOW_HIT);
159
		}
160
161
		return projectileEntity;
162
	}
163
164
	@Override
165
	protected int getDurabilityUse(final ItemStack projectile) {
166
		return projectile.is(Items.FIREWORK_ROCKET) ? 3 : 1;
167
	}
168
169
	public void performShooting(
170
		final Level level,
171
		final LivingEntity shooter,
172
		final InteractionHand hand,
173
		final ItemStack weapon,
174
		final float power,
175
		final float uncertainty,
176
		final @Nullable LivingEntity targetOverride
177
	) {
178
		if (level instanceof ServerLevel serverLevel) {
179
			ChargedProjectiles charged = weapon.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY);
180
			if (charged != null && !charged.isEmpty()) {
181
				List<ItemStack> projectiles = charged.itemCopies().toList();
182
				this.shoot(serverLevel, shooter, hand, weapon, projectiles, power, uncertainty, shooter instanceof Player, targetOverride);
183
				if (shooter instanceof ServerPlayer player) {
184
					CriteriaTriggers.SHOT_CROSSBOW.trigger(player, weapon);
185
					player.awardStat(Stats.ITEM_USED.get(weapon.getItem()));
186
				}
187
			}
188
		}
189
	}
190
191
	private static float getShotPitch(final RandomSource random, final int index) {
192
		return index == 0 ? 1.0F : getRandomShotPitch((index & 1) == 1, random);
193
	}
194
195
	private static float getRandomShotPitch(final boolean highPitch, final RandomSource random) {
196
		float rangeDecider = highPitch ? 0.63F : 0.43F;
197
		return 1.0F / (random.nextFloat() * 0.5F + 1.8F) + rangeDecider;
198
	}
199
200
	@Override
201
	public void onUseTick(final Level level, final LivingEntity entity, final ItemStack itemStack, final int ticksRemaining) {
202
		if (!level.isClientSide()) {
203
			CrossbowItem.ChargingSounds sounds = getChargingSounds(itemStack);
204
			float tickPercent = (float)(itemStack.getUseDuration(entity) - ticksRemaining) / getChargeDuration(itemStack, entity);
205
			if (tickPercent < 0.2F) {
206
				this.startSoundPlayed = false;
207
				this.midLoadSoundPlayed = false;
208
			}
209
210
			if (tickPercent >= 0.2F && !this.startSoundPlayed) {
211
				this.startSoundPlayed = true;
212
				sounds.start().ifPresent(sound -> level.playSound(null, entity.getX(), entity.getY(), entity.getZ(), sound.value(), SoundSource.PLAYERS, 0.5F, 1.0F));
213
			}
214
215
			if (tickPercent >= 0.5F && !this.midLoadSoundPlayed) {
216
				this.midLoadSoundPlayed = true;
217
				sounds.mid().ifPresent(sound -> level.playSound(null, entity.getX(), entity.getY(), entity.getZ(), sound.value(), SoundSource.PLAYERS, 0.5F, 1.0F));
218
			}
219
220
			if (tickPercent >= 1.0F && !isCharged(itemStack) && tryLoadProjectiles(entity, itemStack)) {
221
				sounds.end()
222
					.ifPresent(
223
						sound -> level.playSound(
224
							null,
225
							entity.getX(),
226
							entity.getY(),
227
							entity.getZ(),
228
							sound.value(),
229
							entity.getSoundSource(),
230
							1.0F,
231
							1.0F / (level.getRandom().nextFloat() * 0.5F + 1.0F) + 0.2F
232
						)
233
					);
234
			}
235
		}
236
	}
237
238
	@Override
239
	public int getUseDuration(final ItemStack itemStack, final LivingEntity user) {
240
		return 72000;
241
	}
242
243
	public static int getChargeDuration(final ItemStack crossbow, final LivingEntity user) {
244
		float duration = EnchantmentHelper.modifyCrossbowChargingTime(crossbow, user, 1.25F);
245
		return Mth.floor(duration * 20.0F);
246
	}
247
248
	@Override
249
	public ItemUseAnimation getUseAnimation(final ItemStack itemStack) {
250
		return ItemUseAnimation.CROSSBOW;
251
	}
252
253
	private static CrossbowItem.ChargingSounds getChargingSounds(final ItemStack itemStack) {
254
		return EnchantmentHelper.pickHighestLevel(itemStack, EnchantmentEffectComponents.CROSSBOW_CHARGING_SOUNDS).orElse(DEFAULT_SOUNDS);
255
	}
256
257
	private static float getPowerForTime(final int timeHeld, final ItemStack itemStack, final LivingEntity holder) {
258
		float pow = (float)timeHeld / getChargeDuration(itemStack, holder);
259
		if (pow > 1.0F) {
260
			pow = 1.0F;
261
		}
262
263
		return pow;
264
	}
265
266
	@Override
267
	public boolean useOnRelease(final ItemStack itemStack) {
268
		return itemStack.is(this);
269
	}
270
271
	@Override
272
	public int getDefaultProjectileRange() {
273
		return 8;
274
	}
275
276
	public enum ChargeType implements StringRepresentable {
277
		NONE("none"),
278
		ARROW("arrow"),
279
		ROCKET("rocket");
280
281
		public static final Codec<CrossbowItem.ChargeType> CODEC = StringRepresentable.fromEnum(CrossbowItem.ChargeType::values);
282
		private final String name;
283
284
		ChargeType(final String name) {
285
			this.name = name;
286
		}
287
288
		@Override
289
		public String getSerializedName() {
290
			return this.name;
291
		}
292
	}
293
294
	public record ChargingSounds(Optional<Holder<SoundEvent>> start, Optional<Holder<SoundEvent>> mid, Optional<Holder<SoundEvent>> end) {
295
		public static final Codec<CrossbowItem.ChargingSounds> CODEC = RecordCodecBuilder.create(
296
			i -> i.group(
297
					SoundEvent.CODEC.optionalFieldOf("start").forGetter(CrossbowItem.ChargingSounds::start),
298
					SoundEvent.CODEC.optionalFieldOf("mid").forGetter(CrossbowItem.ChargingSounds::mid),
299
					SoundEvent.CODEC.optionalFieldOf("end").forGetter(CrossbowItem.ChargingSounds::end)
300
				)
301
				.apply(i, CrossbowItem.ChargingSounds::new)
302
		);
303
	}
304
}
305

Decompiled Minecraft 26.3 source of CrossbowItem (net/minecraft/world/item/CrossbowItem.java) with Mojang official mappings, stored verbatim on the site.