Jump to content

Recommended Posts

Posted

So I made a post not long ago about a similar issue, but neglected to mention that my tile entity was a model, and so the usual getIcon method doesn't do much. I have seen models be rotated depending on where the player is/is looking in Mr. Crayfish's Furniture mod (so it is possible), and was wondering how to get a similar effect.

 

Thanks in advance,

 

-Whyneb360

Posted

I did this a little while ago in a since-abandoned mod, so maybe take it with a grain of salt, but looking back at my code, in my Renderer class right before the actual model.render, I rotated it with:

[embed=425,349]GL11.glRotatef(/*some rotation variable*/, 0.0F, 1.0F, 0.0F);[/embed]

As far as getting that rotation variable, you'd probably base it off of the metadata like normal. If you have trouble like that, I'm willing to bet that in your earlier post that you mentioned people explain it. The only real difference is rather than picking an image based off of metadata, you pick a rotation angle (in degrees).

Posted

I have been messing around with this idea a bit, but all I have is this - doesn't work yet:

 

Block Class

public static int metadir = 1;

public void onBlockPlacedBy(World p_149689_1_, int p_149689_2_, int p_149689_3_, int p_149689_4_, EntityLivingBase p_149689_5_, ItemStack p_149689_6_)
    {
        int l = MathHelper.floor_double((double)(p_149689_5_.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        int i1 = p_149689_1_.getBlockMetadata(p_149689_2_, p_149689_3_, p_149689_4_) & 4;

        if (l == 0)
        {
            p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 2 | i1, 2);
            metadir = 1;
        }

        if (l == 1)
        {
            p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 1 | i1, 2);
            metadir = 2;
        }

        if (l == 2)
        {
            p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 3 | i1, 2);
            metadir = 3;
        }

        if (l == 3)
        {
            p_149689_1_.setBlockMetadataWithNotify(p_149689_2_, p_149689_3_, p_149689_4_, 0 | i1, 2);
            metadir = 4;
        }
        
        switch (metadir) {
        case 1:            System.out.println("1");
        break;
        case 2:            System.out.println("2");
        break;
        case 3:            System.out.println("3");
        break;
        case 4:            System.out.println("4");
        break;
        default: break;

        }
    }

 

Render Class

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

int dir = BoardProp.metadir;

public RenderBoard() {
	this.model = new ModelBoard();
}

@Override
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);



		this.bindTexture(texture);

		GL11.glPushMatrix();
			this.model.renderModel(0.0625F);
		GL11.glPopMatrix();

	GL11.glPopMatrix();
}
}

 

Any help would be appreciated

 

-Whyneb360

Posted

That is not what static is for.  If you want to save the direction as metadata, save it as metadata, which you're doing and then ignoring in favor of the static variable.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

That's what I though originally, but when I take away the static variable I get an error with

 

int dir = BoardProp.metadir;

 

I imagine I am just missing something obvious, so apologies in advance

Posted

Use

world.getBlockMetadata(x,y,z)

to get the metadata. You can get the world with

tileEntity.getWorldObj()

  Also, while this doesn't have to do with your block not being the proper direction,  why do you have a switch statement to figure out what to print for your metadata? You can just do

System.out.println(metadir)

Posted

So with the world.getBlockMetadata, does that replace the getBlockNotify thing or is it meant to go somewhere else? Also, where would I put the tileEntity.getWorldObj() as I already have a parameter 'World world' for getting the world. And sorry, the switch statement was just me trying out some different ideas when I was testing

 

Here is my code now (Forgive me if I placed the world.getBlockMetadata in the wrong place):

 

public int metadir;

public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack)
    {
        int l = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        int i1 = world.getBlockMetadata(x, y, z) & 4;

        if (l == 0)
        {
        	world.getBlockMetadata(x,y,z);
            metadir = 0;
            System.out.println("0");
        }

        if (l == 1)
        {
        	world.getBlockMetadata(x,y,z);
            metadir = 1;
            System.out.println("1");
        }

        if (l == 2)
        {
        	world.getBlockMetadata(x,y,z);
            metadir = 2;
            System.out.println("2");
        }

        if (l == 3)
        {
        	world.getBlockMetadata(x,y,z);
            metadir = 3;
            System.out.println("3");
        }
    }

 

And:

 

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

public RenderBoard() {
	this.model = new ModelBoard();
}	

@Override
public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float f) {
	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(metadir * (-90F), 0F, 1F, 0F);



		this.bindTexture(texture);

		GL11.glPushMatrix();
			this.model.renderModel(0.0625F);
		GL11.glPopMatrix();

	GL11.glPopMatrix();
}

 

Though I still haven't figured out how to reference the metadir from my directional methods into my class with the GL11.glRotatef stuff.

 

Thanks,

 

-Whyneb360

Posted

Get rid of

public int metadir;

Use setBlockMetadata when placing the block.  A call to getBlockMetadata that you do nothing with is useless.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Getting the metadata while in the render class is precisely what world.getBlockMetadata() is for. Your block class was fine, except for the odd choice of switch statement. GET block metadata is, as one might expect, for GETTING the metadata. So first you SET it form the Block class, like you originally did, with the SETBlockMetadataWithNotify method. Then, in  your renderer class, you GET it with the world.GETBlockMetadata method. In your renderer class, you don't already have a world variable, so that's what tileEntity.getWorldObj() is for. So this way, by setting the metadad when you place it in the block class then getting it in the renderer class, you pass your directional information from your block to your renderer.

Posted

Again, sorry if I have made a rookie mistake, but should I be putting the tileEntity.getWorldObj() in the renderTileEntityAt method and then have the world.getBlockMetadata stright after that? If so, how should I tell the Java that world is the above tileEntity line? This is what I have now (Block class unchanged):

 

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

public RenderBoard() {
	this.model = new ModelBoard();
}	

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
	tileEntity.getWorldObj();
	int dir = world.getBlockMetadata(x, y, z);

	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);


		this.bindTexture(texture);

		GL11.glPushMatrix();
			this.model.renderModel(0.0625F);
		GL11.glPopMatrix();

	GL11.glPopMatrix();
}


}

 

Thanks for all your help so far

Posted

World world = tileEntity.getWorldObj(). Or World potato = tileEntity.getWorldObj(), it doesn't really matter, as long as you then put potato.getBlockMetadata(). Its just a variable assignment :/ . You'll also need to actually set dir equal to world.getBlockMetadata(). world.getBlockMetadata() is just a method that returns a value (an integer in this case, which is equal to the block's metadata). It doesn't actually change dir on its own- you need to right dir = world.getBlockMetadata(x,y,z); . It seems you are a little unfamiliar with Java, so I suggest looking at at least a few general purpose Java tutorials before going much further with your mod. You can find a million free ones on the internet.

Posted

Seeing the kind of stuff I want to do in my mod, and given my limited understanding of the environment, I will definitely be taking up some Java courses to get the basics down. Until I do though, I am getting an error here:

 

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
	World world = tileEntity.getWorldObj();
	int dir = world.getBlockMetadata(x, y, z);


	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);


		this.bindTexture(texture);

		GL11.glPushMatrix();
			this.model.renderModel(0.0625F);
		GL11.glPopMatrix();

	GL11.glPopMatrix();
}

 

at int dir = world.getBlockMetadata(x, y, z) it wants me to change getBlockMetadata to getBlock. Specifically it says that getBlockMetadata (int, int, int) is not applicable for the arguments double, double, double. Any ideas?

Posted

x, y, and z are doubles. world.getBlockMetadata expects integer parameters. You can solve this just by casting x, y and z to integers. If you don't know how, look at how you cast them to floats in the GL11.glTranslatef() method and, again, I really suggest looking at a java tutorial or two.

Posted

Okay, at this point, I have this code:

 

Render:

 

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

public RenderBoard() {
	this.model = new ModelBoard();
}	

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
	World world = tileEntity.getWorldObj();
	int dir = world.getBlockMetadata((int)x, (int)y, (int)z);


	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (90F), 0F, 1F, 0F);


		this.bindTexture(texture);

		GL11.glPushMatrix();
			this.model.renderModel(0.0625F);
		GL11.glPopMatrix();

	GL11.glPopMatrix();
}
}

 

Block Class:

 

public class BoardProp extends BlockContainer {

public BoardProp(Material material) {
	super(material);

	this.setCreativeTab(DesconCreativeTabs.tabGeneral);
	this.setHarvestLevel("axe", 1);
	this.setHardness(1F);
	this.setBlockBounds(0F, 0F, 1F, 1F, 1F, 0.875F);
	this.setBlockTextureName(Main.modID + ":" + "textures/blocks/board.png");
}

public int getRenderType() {
	return -1;
}

public boolean isOpaqueCube() {
	return false;
}

public boolean renderAsNormalBlock() {
	return false;
}

@Override
public TileEntity createNewTileEntity(World var1, int var2) {
	return new TileEntityBoard();
}

@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
	this.blockIcon = iconRegister.registerIcon(Main.modID + ":" + this.getUnlocalizedName().substring(5));
}

//Directional Bollocks

public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack)
    {
        int l = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        int i1 = world.getBlockMetadata(x, y, z) & 4;

        if (l == 0)
        {
            world.setBlockMetadataWithNotify(x, y, z, 1 | i1, 2);
            System.out.println("0");
        }

        if (l == 1)
        {
            world.setBlockMetadataWithNotify(x, y, z, 2 | i1, 2);
            System.out.println("1");
        }

        if (l == 2)
        {
            world.setBlockMetadataWithNotify(x, y, z, 3 | i1, 2);
            System.out.println("2");
        }

        if (l == 3)
        {
            world.setBlockMetadataWithNotify(x, y, z, 4 | i1, 2);
            System.out.println("3");
        }
    }
}

 

But it still doesn't work. Anything look wrong?

Posted

Hm. Well, at this point I'm basically just comparing your code to mine, because I'm not exactly an expert on openGL myself. With that in mind, I call GL11.glPushMatrix() before I do either of the rotations, rather than after both of them, which you do. Also, I don't think this would really affect anything, but I don't think your i1 variable in your block class does anything. The metadata for the block before you set it is presumably 0, and 0&4=0. Any number | 0 should be the original number. So I'm pretty sure it doesn't do anything but take up some infinitesimal amount of extra processing power. Again, though, because it doesn't actually do anything, it doesn't do anything BAD either. It just exists, when it probably doesn't have to.

Posted

What "doesn't work"?

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

When I say doesn't work, it loads up the game, and I can place the model, but it faces the same direction no matter which way I face

 

EDIT: I'll clarify that, the Sysout works and changes, but the model doesn't rotate

Posted

So I have attempted some debugging to help determine the error, and it seems that in the code below, the Sysout on the onBlockPlacedBy method is all good, but the Sysout for the 'dir' integer in the Render class is only printing continuous 0s. I imagine this means that the rotation stuff is working, but the metadata isn't being set (that or I got the Sysout wrong). My problem is still that the block placed with no errors, but the model doesn't rotate when it's placed from different directions. The game sometimes gives off an error about the tile entity missing a mapping, but I'm not sure if that has anything to do with it.

 

BoardProp:

public class BoardProp extends BlockContainer {

public BoardProp(Material material) {
	super(material);

	this.setCreativeTab(DesconCreativeTabs.tabGeneral);
	this.setHarvestLevel("axe", 1);
	this.setHardness(1F);
	this.setBlockBounds(0F, 0F, 1F, 1F, 1F, 0.875F);
	this.setBlockTextureName(Main.modID + ":" + "textures/blocks/board.png");
}

public int getRenderType() {
	return -1;
}

public boolean isOpaqueCube() {
	return false;
}

public boolean renderAsNormalBlock() {
	return false;
}

@Override
public TileEntity createNewTileEntity(World var1, int var2) {
	return new TileEntityBoard();
}

@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
	this.blockIcon = iconRegister.registerIcon(Main.modID + ":" + this.getUnlocalizedName().substring(5));
}

//Directional Bollocks

public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack)
    {
        int l = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;

        if (l == 0)
        {
            world.setBlockMetadataWithNotify(x, y, z, 0, l);
            System.out.println("0");
        }

        if (l == 1)
        {
            world.setBlockMetadataWithNotify(x, y, z, 1, l);
            System.out.println("1");
        }

        if (l == 2)
        {
            world.setBlockMetadataWithNotify(x, y, z, 2, l);
            System.out.println("2");
        }

        if (l == 3)
        {
            world.setBlockMetadataWithNotify(x, y, z, 3, l);
            System.out.println("3");
        }
    }
}

 

RenderBoard:

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

public RenderBoard() {
	this.model = new ModelBoard();
}	

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
	World world = tileEntity.getWorldObj();
	int dir = world.getBlockMetadata((int)x, (int)y, (int)z);

	System.out.println(dir);

	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);

		this.bindTexture(texture);

		this.model.renderModel(0.0625F);

	GL11.glPopMatrix();
}
}

 

Thanks,

 

-Whyneb360

Posted

I believe the issue now is in your block code, where you do

world.setBlockMetadataWithNotify(x, y, z, 0, l);

The last parameter of the setBlockMetadataWithNotify method is a flag that tells minecraft what to notify about the change to metadata. As a general rule, you usually want it to be 2 (so it notifies the client), and here, where you're dealing with a client-side thing like the direction a model is rendered in, you DEFINITELY want to. Instead, you're setting it to l, which could be 0,1,2, or 3. So what's probably happening is the metadata is set correctly server side, but never passed to the client. So when the renderer class, which only runs on the client side iirc, tries to get the block metadata, it gets the block metadata for the client version of the world, which hasn't changed. Also, because you only ever set the metadata to the value of l in the first place, you can just replace the whole if (l == x) {} set of if statements with

world.setBlockMetadataWithNotify(x,y,z,l,2);
System.out.println(l); //System.out.println is more than robust enough to deal with integers on its own, without you converting them to strings first.

It's much cleaner.

Posted

Usually you want to pass 3 so that the change notifies neighbors.  In this case a 2 is sufficient as the block placement alerted neighbors anyway.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Thanks for the help, but it still isn't placing the way I am facing. I only changed the render class, so I will re-post that (in case I messed something up)

 

public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack)
    {
        int l = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        
        world.setBlockMetadataWithNotify(x, y, z, l, 2);
        System.out.println(l);
        
    }
}

Posted

Is there any other way you would be able to do it? If not, what do I have to change in my code to make it work. Like I said in one of my above posts, the Sysout in:

public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack)
    {
        int l = MathHelper.floor_double((double)(player.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3;
        
        world.setBlockMetadataWithNotify(x, y, z, l, 2);
        System.out.println(l);
        
    }
}

works, but the Sysout in:

public class RenderBoard extends TileEntitySpecialRenderer {

private static final ResourceLocation texture = new ResourceLocation(Main.modID + ":" + "textures/props/BoardTexture.png");

private ModelBoard model;

public RenderBoard() {
	this.model = new ModelBoard();
}	

@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) {
	World world = tileEntity.getWorldObj();
	int dir = world.getBlockMetadata((int)x, (int)y, (int)z);

	System.out.println(dir);

	GL11.glPushMatrix();
		GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);
		GL11.glRotatef(180, 0F, 0F, 1F);
		GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);

		this.bindTexture(texture);

		this.model.renderModel(0.0625F);

	GL11.glPopMatrix();
}
}

Doesn't work (just puts out a constant stream of 0s when one of the blocks is placed in the world. I'm not exactly sure, but I would hazard a guess that the metadata is being stored or read properly.

 

Thanks,

 

-Whyneb360

Posted

public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f)

 

x, y and z are referring to the rendering location, which is not centered on the world center 0,0,0, but actually on the player position.

 

Use tileEntity.xCoord, .yCoord and .zCoord to get the correct world coordinates of your TileEntity.

 

The renderer still needs to be translated with the rendering coords x, y, z, though, so keep

GL11.glTranslatef((float)x + 0.5F, (float)y + 1.5F, (float)z + 0.5F);

as it is!

Don't ask for support per PM! They'll get ignored! | If a post helped you, click the "Thank You" button at the top right corner of said post! |

mah twitter

This thread makes me sad because people just post copy-paste-ready code when it's obvious that the OP has little to no programming experience. This is not how learning works.

Posted

I apolologise in advance, but as I am new to forge, I am not quite sure where to put the tileEntity.xCoord, .yCoord and .zCoord. I tried replacing the double x, y and z, but it didn't work, and I didn't think that would be right. If it was for World world = tileEntrity.xCoord, it throws and error when written like that. Sorry if I am missing something obvious, but I am eager to learn how to do this.

 

EDIT: Okay, got it to work, so thanks. Do you have any suggestions for making the hitbox rotate as well?

this.setBlockBounds(0F, 0F, 1F, 1F, 1F, 0.875F);

is what I have at the moment

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

    • 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?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

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