我们本次在fabric中加入自己制作的音效。
1.init包中新建一个类SoundInit,注册所有的模组音效:
SoundInit.java
package net.joy187.joyggd.init;
import net.joy187.joyggd.ModMain;
import net.minecraft.sound.SoundEvent;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class SoundInit {
//这些是音效名称
public static SoundEvent PELEBALL;
public static SoundEvent MUMMYKILL;
private static SoundEvent registerSoundEvent(String name) {
Identifier id = new Identifier(ModMain.MOD_ID, name);
return Registry.register(Registry.SOUND_EVENT, id, new SoundEvent(id));
}
public static void registerSounds() {
//每个名称均与后面的字符串一一对应
PELEBALL = registerSoundEvent("entity.peleball");
MUMMYKILL = registerSoundEvent("entity.mummykill");
}
}
之后在项目主类中初始化该音效类:
ModMain.java
public class ModMain implements ModInitializer {
@Override
public void onInitialize() {
ModConfigs.registerConfigs();
ItemInit.registerModItems();
BlockInit.registerModBlocks();
EffectInit.registerEffects();
//添加音效类注册事件
SoundInit.registerSounds();
ModWorldGen.generateWorldGen();
GeckoLib.initialize();
}
}
2.之后我们可以将注册的声音名称进行使用:
1.改变物品使用音效
playerIn.world.playSound(playerIn, playerIn.getBlockPos(), SoundInit.PELEBALL, SoundCategory.PLAYERS, 1.5F, 0.8F / (playerIn.world.getRandom().nextFloat() * 0.4F + 0.8F));
2.改变生物音效:
protected SoundEvent getAmbientSound() {
int co=this.random.nextInt(3);
if(co==1) return SoundInit.PELEBALL;
return SoundInit.MUMMYKILL;
}
protected SoundEvent getHurtSound(DamageSource source) {
return SoundInit.PELEBALL;
}
protected SoundEvent getDeathSound() {
return SoundInit.MUMMYKILL;
}
3.将我们的音效文件(.ogg)放入resources\assets\你的modid\sounds\entity
中:
之后在资源包中新建一个sounds.json
文件:
将我们之前的音效文件信息写在sounds.json
中,注意名称与第一步registerSounds()
中的要对应:
sounds.json
{
"entity.peleball":{
"category":"entity",
"subtitle" :"entity.peleball.sub",
"sounds":[{ "name": "joyggd:entity/peleball", "stream":true }]
},
"entity.mummykill":{
"category":"entity",
"subtitle" :"entity.mummykill.sub",
"sounds":[{ "name": "joyggd:entity/mummykill", "stream":true }]
}
}