Jump to content

Recommended Posts

Posted

So, generally I have been using 

this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width
				&& mouseY < this.y + this.height;

for setting any of my custom buttons' hover status, but I noticed this won't really work if I have overlapping buttons. In my specific case, this is the issue:

Spoiler

image.png.d88e2ef2c16ec243a1406f0949de2698.png

As you can see, the white keys extend under the black keys, meaning that the aforementioned method of setting a button's isHovered variable would not work, as it would return true for the first key (C) even if its the corresponding black key (C#) that is hovered, as long as it is within the width of the first key

Spoiler

image.png.3f94af2d668f81c2152e62c88096ecf0.png

The green is the area that would return true using the method I mentioned above for the white key, and red for the black, but the blue area esults in both the white and black keys getting their isHovered variable set to true, while the desired behaviour is to only have the black key's isHovered value to be true, and the white key's false.

 

While I know I can use 2 different checks to check the white key in this manner, green first check and yellow second:

Spoiler

image.png.cc10a840444b7960171d8dc9b99c6cce.png

I was wondering if there is a better method to do this, without having to hardcode the checks for every single key, as all have different indentations regarding black keys.

 

Thanks for taking the time to read this, and I am looking forward to see what you guys suggest.

Posted

One option would be to have it check if any black keys are hovered first, and if so, completely skip the check for white keys. You'd probably have to restructure the way you're performing checks whenever the user clicks, but it's certainly doable.

I'm eager to learn and am prone to mistakes. Don't hesitate to tell me how I can improve.

Posted
18 minutes ago, imacatlolol said:

One option would be to have it check if any black keys are hovered first, and if so, completely skip the check for white keys. You'd probably have to restructure the way you're performing checks whenever the user clicks, but it's certainly doable.

It's a nice idea, but how would I go about doing it? The white key in which I would need to check if a black key is being hovered does not have access to the black key, so I can't do that

 

For reference: Button class

Spoiler

package com.spacejet.more_music.client.gui.widget.button;

import com.spacejet.more_music.Main;

import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.gui.GuiUtils;
import net.minecraftforge.fml.client.gui.widget.ExtendedButton;

public class PinaoKeyButton extends ExtendedButton
{
	private static final ResourceLocation KEY_TEXTURES = new ResourceLocation(Main.MOD_ID, "textures/gui/keys.png");

	private int type;

	/**
	 * 
	 * @param xPos    : x position of the button
	 * @param yPos    : y position of the button
	 * @param width   : width of the button
	 * @param height  : height of the button
	 * @param type    : determines what key it is supposed to be, so the texture can
	 *                be drawn correctly of a black key
	 * @param handler
	 */
	public PinaoKeyButton(int xPos, int yPos, int width, int height, int type, IPressable handler)
	{
		super(xPos, yPos, width, height, "", handler);
		this.type = type;
	}

	@Override
	public void renderButton(int mouseX, int mouseY, float partial)
	{
		Minecraft mc = Minecraft.getInstance();
//		setHoverStatus(mouseX, mouseY);
		this.isHovered = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width
				&& mouseY < this.y + this.height;
		drawTexture();
		this.renderBg(mc, mouseX, mouseY);
	}

	private void drawTexture()
	{
		int yOffset = 0;

		if (this.isHovered)
			yOffset = 51;

		switch (type)
		{
			case 1:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 0, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 2:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 15, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 3:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 30, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 4:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 45, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 5:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 60, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 6:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 75, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 7:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 90, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset());
				break;
			case 8:
				GuiUtils.drawContinuousTexturedBox(KEY_TEXTURES, this.x, this.y, 105, yOffset, this.width, this.height,
						this.width, this.height, 2, 3, 2, 2, this.getBlitOffset() + 2);
				break;
		}
	}
}

 

Screen class:

Spoiler

package com.spacejet.more_music.client.gui;

import com.mojang.blaze3d.systems.RenderSystem;
import com.spacejet.more_music.Main;
import com.spacejet.more_music.client.gui.widget.button.PinaoKeyButton;
import com.spacejet.more_music.container.AdvancedNoteBlockContainer;

import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class AdvancedNoteBlockScreen extends ContainerScreen<AdvancedNoteBlockContainer>
{
	private static final ResourceLocation BACKGROUND_TEXTURE = new ResourceLocation(Main.MOD_ID,
			"textures/gui/container/advanced_note_block.png");

	public AdvancedNoteBlockScreen(AdvancedNoteBlockContainer screenContainer, PlayerInventory inv,
			ITextComponent titleIn)
	{
		super(screenContainer, inv, titleIn);
		this.guiLeft = 0;
		this.guiTop = 0;
		this.xSize = 175;
		this.ySize = 179;
	}

	@Override
	public void render(final int mouseX, final int mouseY, final float partialTicks)
	{
		this.renderBackground();
		super.render(mouseX, mouseY, partialTicks);
		this.renderHoveredToolTip(mouseX, mouseY);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
	{
		super.drawGuiContainerForegroundLayer(mouseX, mouseY);
		this.font.drawString(this.title.getFormattedText(), 8.0f, 6.0f, 4210752);
		this.font.drawString(this.playerInventory.getDisplayName().getFormattedText(), 8.0F,
				(float) (this.ySize - 96 + 2), 4210752);
	}

	@Override
	protected void init()
	{
		int x = this.width / 2 - this.xSize / 2;
		int y = this.height / 2 - this.ySize / 2;

		// The flags are 1:C, 2:D, 3:E... (8:any accidental note)
		this.addButton(new PinaoKeyButton(x + 20, y + 18, 8, 34, 8, $ -> {System.out.println("C#");})); // The key of C#/Db
		this.addButton(new PinaoKeyButton(x + 36, y + 18, 8, 34, 8, $ -> {System.out.println("D#");})); // The key of D#/Eb
		this.addButton(new PinaoKeyButton(x + 61, y + 18, 8, 34, 8, $ -> {System.out.println("F#");})); // The key of F#/Gb
		this.addButton(new PinaoKeyButton(x + 77, y + 18, 8, 34, 8, $ -> {System.out.println("G#");})); // The key of G#/Ab
		this.addButton(new PinaoKeyButton(x + 93, y + 18, 8, 34, 8, $ -> {System.out.println("A#");})); // The key of A#/Bb
		this.addButton(new PinaoKeyButton(x + 11, y + 18, 14, 50, 1, $ -> {System.out.println("C");})); // The key of C
		this.addButton(new PinaoKeyButton(x + 25, y + 18, 14, 50, 2, $ -> {System.out.println("D");})); // The key of D
		this.addButton(new PinaoKeyButton(x + 39, y + 18, 14, 50, 3, $ -> {System.out.println("E");})); // The key of E
		this.addButton(new PinaoKeyButton(x + 53, y + 18, 14, 50, 4, $ -> {System.out.println("F");})); // The key of F
		this.addButton(new PinaoKeyButton(x + 67, y + 18, 14, 50, 5, $ -> {System.out.println("G");})); // The key of G
		this.addButton(new PinaoKeyButton(x + 81, y + 18, 14, 50, 6, $ -> {System.out.println("A");})); // The key of A
		this.addButton(new PinaoKeyButton(x + 95, y + 18, 14, 50, 7, $ -> {System.out.println("B");})); // The key of B

		super.init();
	}
	
	@Override
	public boolean isPauseScreen()
	{
		return false; // Don't pause the game when this screen is open
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
	{
		RenderSystem.color4f(1.0f, 1.0f, 1.0f, 1.0f);
		this.minecraft.getTextureManager().bindTexture(BACKGROUND_TEXTURE);

		int startX = (this.width - this.xSize) / 2;
		int startY = (this.height - this.ySize) / 2;

		// Screen#blit draws a part of the current texture (assumed to be 256x256) to
		// the screen
		// The parameters are (x, y, u, v, width, height)

		this.blit(startX, startY, 0, 0, this.xSize, this.ySize);
	}

}

 

 

Posted

Well there's a few options, but here's my initial idea. You could make a couple methods for adding black or white keys respectively and then have those methods call addButton and also place the keys in separate lists. Then, you could override the mouseClicked function of your screen and have it first iterate through the black keys and check the result of their mouseClicked function, then the white keys, and then fall back to the default behavior.

I'm eager to learn and am prone to mistakes. Don't hesitate to tell me how I can improve.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.