Jump to content

[1.7.10] Centering a gui?


Recommended Posts

Posted

Hi, I recently made a gui that opens when you right click and item. It works good except I don't know how to center it. I could hard-code the coordinates where the gui renders in, but then if the screen gets bigger of smaller it won't be centered anymore. Is there a way to do this?

Posted

Ok, I tried it, the background disappeared:

3IbHFTt.png

:/ Did I do it wrong?

...
ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft(), Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayWidth);

        int backX = sr.getScaledWidth();
        int backY = sr.getScaledHeight();

        ResourceLocation background = new ResourceLocation(SignificantAdvancements.MODID, "textures/guis/lexiconBackground.png");
        Minecraft.getMinecraft().renderEngine.bindTexture(background);

        this.drawTexturedModalRect(backX, backY, 0, 0, guiWidth, guiHeight);
...

Posted

public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height)

 

You're drawing it off of the screen. X and Y respectively should be

 

(backX - guiWidth) / 2

(backY - guiHeight) / 2

Posted

Then your guiHeight would be wrong.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

I don't know if you're still having problems, but the

 

public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height)

 

method you are using assumes a texture size of 256x256. If your texture is a unique size, drawModalRectWithCustomSizedTexture(...) may provide better results.

 

Posted

Umm... Isn't that what this does:

...
int backX = sr.getScaledWidth();
int backY = sr.getScaledHeight();

this.drawTexturedModalRect((backX - guiWidth) / 2, (backY - guiHeight) / 2, 0, 0, guiWidth, guiHeight);

Posted

My gui height is right. Could it be because the display has to be an uneven ratio? I mean like the display being 1280 x 720. So why would I use / 2 on both the x and y values? Shouldn't the y value have something like / 4? If I'm not making sense just tell me. :/

Posted

Umm... Isn't that what this does:

...
int backX = sr.getScaledWidth();
int backY = sr.getScaledHeight();

this.drawTexturedModalRect((backX - guiWidth) / 2, (backY - guiHeight) / 2, 0, 0, guiWidth, guiHeight);

Yes, it is the same, but why add stuff that's already there :o?

My gui height is right. Could it be because the display has to be an uneven ratio? I mean like the display being 1280 x 720. So why would I use / 2 on both the x and y values? Shouldn't the y value have something like / 4? If I'm not making sense just tell me. :/

Well, devding by 2 gives the middle value...

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

Posted

I think full code is needed to resolve this issue.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

Did you try what yyrkoon said about using drawModalRectWithCustomSizedTexture instead. That's what I normally use and that could be the issue.

 

drawModalRectWithCustomSizedTexture((backX - guiWidth) / 2, (backY - guiHeight) / 2, 0, 0, guiWidth, guiHeight, guiWidth, guiHeight);

Posted

As i said, to center your WHOLE gui, and without worriing to center EACH element, in gui constructor add this, and then use guiTop and guiLeft as offset depart point...:

this.guiLeft = (this.width - this.xSize) / 2;
        this.guiTop = (this.height - this.ySize) / 2;

What happens here, i may represent as:

this.guiLeft = this.width / 2 - this.xSize / 2

What this does: finds middle of screen (width/2) and substracts half of size of gui (xSize/2), in result middle of gui is middle of screen.

But using laws of maths, we can convert this formula to

this.guiLeft = (this.width - this.xSize) / 2

And all that is left to do: each element draw relative to guiLeft and guiTop. Example of drawing background:

this.drawTexturedModalRect(guiLeft, guiTop, 0, 0, guiWidth, guiHeight);

Example of drawing element:

this.drawTexturedModalRect(guiLeft + 123, guiTop + 59, 0, 0, 16, 16);

 

 

PS: like that you don't need to worry about scaled resolution stuff.

BTW: if you haven't access to gui constructor, do this in gui init event.

Posted

Did you try what yyrkoon said about using drawModalRectWithCustomSizedTexture instead. That's what I normally use and that could be the issue.

 

drawModalRectWithCustomSizedTexture((backX - guiWidth) / 2, (backY - guiHeight) / 2, 0, 0, guiWidth, guiHeight, guiWidth, guiHeight);

 

Well, that method doesn't exist for me. :/

 

I think full code is needed to resolve this issue.

 

Ok, here is my gui class:

public class GuiLexicon extends GuiScreen {
    int guiWidth = 192;
    int guiHeight = 256;

    static int GUI_ID = 30;

    @Override
    public void drawScreen(int mouseX, int mouseY, float par3) {
        super.drawScreen(mouseX, mouseY, par3);

        ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft(), Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayWidth);

        int backX = sr.getScaledWidth();
        int backY = sr.getScaledHeight();

        this.drawTexturedModalRect((backX - guiWidth) / 2, (backY - guiHeight) / 2, 0, 0, guiWidth, guiHeight);

        int stringWidth = this.fontRendererObj.getStringWidth("Lexicon of Knowledge");

        ResourceLocation background = new ResourceLocation(SignificantAdvancements.MODID, "textures/guis/lexiconBackground.png");
        Minecraft.getMinecraft().renderEngine.bindTexture(background);

        this.fontRendererObj.drawString("Lexicon of Knowledge", guiWidth - stringWidth, 50, 0x00FFFF, true);
    }
}

Posted

Appologies, My head was in 1.8. The method exists in 1.7.10, just not in a user friendly form. The method call for you would be func_146110_a. I've copied the 1.8 call below as well so you can better see what the parameters represent. The internals of the 2 methods are the same. Also these are STATIC methods.

 

For the text, you can use the same formula (backx- stringwidth) / 2. The y position you can use the same value as the y coord of the texture.

 

is it safe to assume you texture is also 192x256? If you can open your texture and pad it's width to 256 with transparency (32px on either side), the scaling won't matter and you can use the same draw rect method you've been using (less math ;) )

 

1.8

public static void drawModalRectWithCustomSizedTexture(int x, int y, float u, float v, int width, int height, float textureWidth, float textureHeight)

 

1.7.10

public static void func_146110_a(int p_146110_0_, int p_146110_1_, float p_146110_2_, float p_146110_3_, int p_146110_4_, int p_146110_5_, float p_146110_6_, float p_146110_7_)

 

Posted

Ok, I just don't understand why I would have to use that method, my gui's texture is 256x256. It isn't a custom texture measurement. But I could try that.

 

Edit: Odd, func_146110_a  doesn't exist either. :/

Posted

Ok, I just don't understand why I would have to use that method, my gui's texture is 256x256. It isn't a custom texture measurement. But I could try that.

 

Edit: Odd, func_146110_a  doesn't exist either. :/

Sorry for repeating, but have you tried what i said you above??? Because it MUST work...

If you're too lazy, here's modified centered code for gui:

public class GuiLexicon extends GuiScreen {
    int guiWidth = 192;
    int guiHeight = 256;
    
    int guiLeft = 0;
    int guiTop = 0;
    
    public GuiLexicon() {
    	guiLeft = (width - guiWidth) / 2;
    	guiTop = (height - guiHeight) / 2;
    }

    static int GUI_ID = 30;

    @Override
    public void drawScreen(int mouseX, int mouseY, float par3) {
        super.drawScreen(mouseX, mouseY, par3);

        Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(SignificantAdvancements.MODID, "textures/guis/lexiconBackground.png"));
        this.drawTexturedModalRect(guiLeft, guiTop, 0, 0, guiWidth, guiHeight);       
        
        int stringWidth = this.fontRendererObj.getStringWidth(I18n.format("lexiconOfKnowledge.lang"));

        this.fontRendererObj.drawString(I18n.format("lexiconOfKnowledge.lang"), guiWidth - stringWidth, 50, 0x00FFFF, true);
    }
}

 

Ps: this is also multi language friendly!!!

And also, func_146110_a  is static and in Gui.class

Posted

Your texture is the right dimension, so you can safely ignore my comments about the drawRect methods.

 

Most vanilla container textures don't use a full 256 height for the background portion though. I think you book might simply be too tall.

Posted

ñaa

same trouble but in 1.8 , the diferense is i wanna keep mi icons in boton left

i could get the  sr.getScaledWidth(); to work properly

int backX = sr.getScaledWidth();

int backY = sr.getScaledHeight();

 

 

later i try to fix them calculating the position the hard way, neither i could make it work and end geting tired of it an let it for later   

 

 

this code works well only when = 2  , normal size in the menu 

            Minecraft mc;
            displayWidth=mc.displayWidth;
            displayHeight=mc.displayHeight;
            guiscale=mc.gameSettings.guiScale;
            
            switch(guiscale)
            {
            case 0: ;break;
            case 3:
            {
            	posX=16; //controls the Icons size
                posY=((displayHeight/2)-25);
                x=40;  //gui size    
            } ;break;
            
            case 2:
            {
            	posX=30; //controls the Icons size
                posY=((displayHeight/2)-60);
                x=40;  //gui size    
            } ;break;
            
            case 1:
            {
            	posX=16; //controls the Icons size
                posY=((displayHeight)-100);
                x=10;  //gui size    
            } ;break;
            
            
            }


       
        //Prepare rendering
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        GL11.glDisable(GL11.GL_LIGHTING);
        
        
        
        if (municion<0)
        {
        municion=0;	
        }	
        
        
        //drawModalRectWithCustomSizedtext0ure(int x, int y,float u,float v,int width,int height,float text0ureWidth,float text0ureHeight);
        
        this.mc.renderEngine.bindTexture(new ResourceLocation(icono0));
        this.drawModalRectWithCustomSizedTexture( (posX - 5), (posY), 0.0F, 0.0F, x, x, xf, xf); //imagen al 60%
        //this.drawModalRectWithCustomSizedtext0ure(posX + 8, posY + 8, 0.0F, 0.0F, 200, 200 , 200.0F, 200.0F);
        
        this.mc.renderEngine.bindTexture(new ResourceLocation(icono1));
        this.drawModalRectWithCustomSizedTexture( (posX + x ), (posY ), 0.0F, 0.0F, (int) (x * 1.5), (x / 3), (xf * 1.5F), (xf / 3) ); //imagen al 60%
        
        this.mc.renderEngine.bindTexture(new ResourceLocation(icono2));
        this.drawModalRectWithCustomSizedTexture( (posX + x ), (posY + (x / 3) ), 0.0F, 0.0F, (int)  (((x * 1.0) / balas ) * municion), (x / 3), (xf * 1.0F), (xf / 3) ); 
        
        this.mc.renderEngine.bindTexture(new ResourceLocation(icono3));
        this.drawModalRectWithCustomSizedTexture( (posX + x ), (posY + ((x / 3) * 2) ), 0.0F, 0.0F, (int) (x * 1.5), (x / 3), (xf * 1.5F), (xf / 3) ); 
        
        
        
        this.mc.fontRendererObj.drawStringWithShadow(text0,  posX, ((posY ) + x) , 0xffcccccc);



Posted

Hmm... Well, I don't know if this matters, but I'm extending GuiScreen. I'm not using GuiContainer or anything. Does that change anything? Surely not. :/

Posted

Hmm... Well, I don't know if this matters, but I'm extending GuiScreen. I'm not using GuiContainer or anything. Does that change anything? Surely not. :/

In gui screen you have guiTop, guiLeft, xSize, ySize predefined for you to center your gui. If you don't extend it, you can center it manualy, as i wrote above.

(Sir, if you're lazy to do it your self, look above: i posted code for your centered gui, you can use it...)

Please reply me, for that i understand that you read this post and tried it...

Posted

 

du not know

coz im doing not just one icon but four and a text that must be aligned whit the first icon,

¿is there a guiDownLeft ¿how do you put it on code

 

thi is how mi gui must look all the time for now just work when the screen size is set to normal

Posted

Hmm... Well, I don't know if this matters, but I'm extending GuiScreen. I'm not using GuiContainer or anything. Does that change anything? Surely not. :/

In gui screen you have guiTop, guiLeft, xSize, ySize predefined for you to center your gui. If you don't extend it, you can center it manualy, as i wrote above.

(Sir, if you're lazy to do it your self, look above: i posted code for your centered gui, you can use it...)

Please reply me, for that i understand that you read this post and tried it...

 

Those fields aren't there :/ They don't exist for me.

 

Edit: I typed them and they showed up red, I looked in the GuiScreen class, not there. They don't exist. :/

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

    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • 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() ); } }  
  • Topics

  • Who's Online (See full list)

    • There are no registered users currently online
×
×
  • Create New...

Important Information

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