Jump to content

Destroy / Remove blocks (10x10x10) when the block is clicked with an item.


Recommended Posts

Posted

Of course, here you go:


import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.TargetBlock;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.event.entity.ProjectileImpactEvent;

import static net.minecraftforge.client.gui.ForgeIngameGui.rayTraceDistance;


public class teleportItem extends Item {
    public teleportItem(Properties pProperties) {
        super(pProperties);
    }


    @Override
    public InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pUsedHand) {

        // entity.pick(rayTraceDistance, 0.0F, false);
        Entity entity = Minecraft.getInstance().getCameraEntity();

        rayTraceDistance = 500.0D;

        HitResult viewedBlock = entity.pick(rayTraceDistance, 0.0F, false);
        Double x = viewedBlock.getLocation().x;
        Double y = viewedBlock.getLocation().y;
        Double z = viewedBlock.getLocation().z;

        y += 1;

        if (!pLevel.isClientSide){
            pPlayer.teleportTo(x, y, z);
        }

        pPlayer.fallDistance = 0.0f;
        rayTraceDistance = 20.0D;

        return super.use(pLevel, pPlayer, pUsedHand);
    }
}

 

Posted

This does not work you need in this case server raytrace, you can take a look at BucketItem#use for an example.
why did you use ForgeIngameGui.rayTraceDistance this makes for me no sense, do you know what it is used for?

Posted

It gets me the x, y, z of my crosshair position. Initial value of the rayTraceDistance is 20.0D, therefore you can only get x, y, z in that specter, however once I increase it, I can get positions from much further. I used it from here: https://github.com/MinecraftForge/MinecraftForge/blob/bb4818630c0c6cdd7c4178b4d77dc406153c2bcb/src/main/java/net/minecraftforge/client/gui/overlay/ForgeGui.java#L680

So you reckon I have to change the way I get x, y and z?

 

Posted
56 minutes ago, Gepardius said:

It gets me the x, y, z of my crosshair position. Initial value of the rayTraceDistance is 20.0D, therefore you can only get x, y, z in that specter, however once I increase it, I can get positions from much further. I used it from here:

ForgeIngameGui.rayTraceDistance is just a double value there is nothing special with it

57 minutes ago, Gepardius said:

So you reckon I have to change the way I get x, y and z?

yes:

1 hour ago, Luis_ST said:

you need in this case server raytrace, you can take a look at BucketItem#use for an example.

Posted

If I use this one:

HitResult viewedBlock = getPlayerPOVHitResult(pLevel, pPlayer, ClipContext.Fluid.NONE);

I can only teleport around 5-10 blocks. Is there another server side method to get rayTrace?

Posted

Btw. If I use pPlayer instead of assigning Entity through Minecraf.getInstance() as below:

@Override
    public InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pUsedHand) {

        // entity.pick(rayTraceDistance, 0.0F, false);
        // Entity entity = Minecraft.getInstance().getCameraEntity();
        
        rayTraceDistance = 500.0D;

        HitResult viewedBlock = pPlayer.pick(rayTraceDistance, 0.0F, false); 
        Double x = viewedBlock.getLocation().x;
        Double y = viewedBlock.getLocation().y;
        Double z = viewedBlock.getLocation().z;

        y += 1;

        if (!pLevel.isClientSide){
            pPlayer.teleportTo(x, y, z);
        }

        pPlayer.fallDistance = 0.0f;
        rayTraceDistance = 20.0D;

        return super.use(pLevel, pPlayer, pUsedHand);
    }

Then it works as before and it solves it right?

Posted (edited)
12 minutes ago, Gepardius said:

Then it works as before and it solves it right?

i'm not sure as far as I can see in the code, yes
test it on a server via runServer

12 minutes ago, Gepardius said:

I can only teleport around 5-10 blocks. Is there another server side method to get rayTrace?

it use the reach distance of the player which is 4.5 by default

Edited by Luis_ST
Posted

The server starts without interruptions, but I'd have to upload the mod into the run folder in order to real-life test it right, which will take some time? For the moment I'll just have to believe it will work on the server as well.

Posted
20 minutes ago, Gepardius said:

but I'd have to upload the mod into the run folder in order to real-life test it right, which will take some time?

No you have to run the runServer gradle task

Note the first time you run the server it stops, since you need to accept the eula,
the second time it generate all missing files but you need to stop the server,
since you need to disable the online mode in the server.properties file

Posted

Hmmm... I've accepted the eula, changed online mode to false and now I only have Minecraft server window open. How do I connect to it? I tried through the client but I must be doing something wrong. 

Posted

Aha. It worked when I connected just with: localhost. 

Everything works normally, except the teleporting. I guess it is not possible to teleport player on the server with:

player.setPos(x, y, z);
// or
player.teleportTo(x, y, z);

Is there another server teleport method?

Posted

I tried with Player#teleportToWithTicket, unfortunately it does not work: 

if (!level.isClientSide) {

	player.teleportToWithTicket(x, y, z);

}

But I can't figure out how to try the ServerPlayer#connection and ServerGamePacketListenerImpl#teleport yet, so I'll have to get back to you once I do :)

Posted
29 minutes ago, Gepardius said:

But I can't figure out how to try the ServerPlayer#connection and ServerGamePacketListenerImpl#teleport yet, so I'll have to get back to you once I do

i guess your variable "player" is a Player, then you need an instance of check if the Player is an ServerPlayer.
Then you can cast your Player to a ServerPlayer.

Btw this is basic java.

  • Like 1
Posted

I am checking the instance now, but I don't know what to input as the last two elements.

if (player instanceof ServerPlayer){
	((ServerPlayer) player).connection.teleport(x, y, z, 0, 0);
}
Posted
1 hour ago, Gepardius said:

I am checking the instance now, but I don't know what to input as the last two elements.

the first one is the y rotation of the player head and the second one is the x rotation of the player head,
you can use 0 if you don't want a specific head look direction

  • Like 1
Posted

Very basic question again... I am not applying changes to the server, when using the InteractionResultHolder method:

@Override
    public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand pUsedHand) {

        rayTraceDistance = 500.D;

        HitResult viewedBlock = player.pick(rayTraceDistance, 0.0F, false);
        Double x = viewedBlock.getLocation().x;
        Double y = viewedBlock.getLocation().y;
        Double z = viewedBlock.getLocation().z;
        y += 1;

        if (player instanceof ServerPlayer){
            System.out.println("nothing happens");
            // player.teleportToWithTicket(x, y, z);
        }

        if (!level.isClientSide) {

            System.out.println("nothing happens");
            ((ServerPlayer) player).connection.teleport(x, y, z, 1, 1);
            // player.teleportToWithTicket(x, y, z);

        }

        rayTraceDistance = 20.0D;
        return super.use(level, player, pUsedHand);
    }

In theory shouldn't both of these ifs be triggered from the server?

Posted
18 minutes ago, Gepardius said:

In theory shouldn't both of these ifs be triggered from the server?

yes, does it not work?

18 minutes ago, Gepardius said:
rayTraceDistance = 500.D;

why did you still use this, you can pass the value (500) directly into Player#pick

Posted

On the client yes, on the server no. Have you got any idea why?

rayTraceDistance = 500.D; I know but later on I might change it through custom leveling.

Full code:

import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.HitResult;
import static net.minecraftforge.client.gui.ForgeIngameGui.rayTraceDistance;


public class teleportItem extends Item {
    public teleportItem(Properties pProperties) {
        super(pProperties);
    }


    @Override
    public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand pUsedHand) {

        rayTraceDistance = 500.D;

        HitResult viewedBlock = player.pick(rayTraceDistance, 0.0F, false);
        Double x = viewedBlock.getLocation().x;
        Double y = viewedBlock.getLocation().y;
        Double z = viewedBlock.getLocation().z;
        y += 1;


        if (player instanceof ServerPlayer){
            System.out.println("nothing happens");
            // player.teleportToWithTicket(x, y, z);
        }

        if (!level.isClientSide) {

            System.out.println("nothing happens");
            ((ServerPlayer) player).connection.teleport(x, y, z, 1, 1);
            // player.teleportToWithTicket(x, y, z);

        }

        rayTraceDistance = 20.0D;
        return super.use(level, player, pUsedHand);
    }
}

 

Posted
2 minutes ago, Gepardius said:

On the client yes, on the server no. Have you got any idea why?

Did you mean Singleplayer with "client"?

1 minute ago, Gepardius said:

I know but later on I might change it through custom leveling.

Could you please explain that in more detail?

Posted

Yes singleplayer with client. No multiplayer through client (localhost).

This one "I know but later on I might change it through custom leveling." is not important for now. Later on I want to implement custom levels, which will increase/decrease this double figure.

Posted
1 minute ago, Gepardius said:

Yes singleplayer with client. No multiplayer through client (localhost).

Then rayTraceDistance is your issue it's in a class which should be only used on client,
remove it since you can not store data like this in a Item, the value will be shared.

If you want to store data in a Item you need to store the data in the related ItemStack.
Therefore i would recommend you to use a Capability.

Posted (edited)

Nope still nothing happens the ifs are never accessed: 

if (player instanceof ServerPlayer){
  System.out.println("nothing happens");
  // player.teleportToWithTicket(x, y, z);
}

if (!level.isClientSide) {

  System.out.println("nothing happens");
  ((ServerPlayer) player).connection.teleport(x, y, z, 1, 1);
  // player.teleportToWithTicket(x, y, z);

}

I thank you for your effort and time. I'll be gone for a few days now, so I won't be able to reply. I appreciate your help!

Edited by Gepardius
Posted

I'm not be able to reproduce your problem, this code works fine in Singleplayer and on Server.
The Logger debug statements are correctly printed on console

Please post the full class of your Item.

	@Override
	public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
		if (player instanceof ServerPlayer serverPlayer) {
			LogUtils.getLogger().debug("ServerPlayer");
			serverPlayer.connection.teleport(serverPlayer.getX(), 100, serverPlayer.getZ(), 0.0F, 0.0F);
		}
		if (!level.isClientSide) {
			LogUtils.getLogger().debug("!isClientSide");
		}
		return super.use(level, player, hand);
	}
  • Like 1

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

    • that happens every time I enter a new dimension.
    • This is the last line before the crash: [ebwizardry]: Synchronising spell emitters for PixelTraveler But I have no idea what this means
    • What in particular? I barely used that mod this time around, and it's never been a problem in the past.
    • Im trying to build my mod using shade since i use the luaj library however i keep getting this error Reason: Task ':reobfJar' uses this output of task ':shadowJar' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. So i try adding reobfJar.dependsOn shadowJar  Could not get unknown property 'reobfJar' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. my gradle file plugins { id 'eclipse' id 'idea' id 'maven-publish' id 'net.minecraftforge.gradle' version '[6.0,6.2)' id 'com.github.johnrengelman.shadow' version '7.1.2' id 'org.spongepowered.mixin' version '0.7.+' } apply plugin: 'net.minecraftforge.gradle' apply plugin: 'org.spongepowered.mixin' apply plugin: 'com.github.johnrengelman.shadow' version = mod_version group = mod_group_id base { archivesName = mod_id } // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17. java.toolchain.languageVersion = JavaLanguageVersion.of(17) //jarJar.enable() println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" minecraft { mappings channel: mapping_channel, version: mapping_version copyIdeResources = true runs { configureEach { workingDirectory project.file('run') property 'forge.logging.markers', 'REGISTRIES' property 'forge.logging.console.level', 'debug' arg "-mixin.config=derp.mixin.json" mods { "${mod_id}" { source sourceSets.main } } } client { // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. property 'forge.enabledGameTestNamespaces', mod_id } server { property 'forge.enabledGameTestNamespaces', mod_id args '--nogui' } gameTestServer { property 'forge.enabledGameTestNamespaces', mod_id } data { workingDirectory project.file('run-data') args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } sourceSets.main.resources { srcDir 'src/generated/resources' } repositories { flatDir { dirs './libs' } maven { url = "https://jitpack.io" } } configurations { shade implementation.extendsFrom shade } dependencies { minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" implementation 'org.luaj:luaj-jse-3.0.2' implementation fg.deobf("com.github.Virtuoel:Pehkui:${pehkui_version}") annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' minecraftLibrary 'luaj:luaj-jse:3.0.2' shade 'luaj:luaj-jse:3.0.2' } // Example for how to get properties into the manifest for reading at runtime. tasks.named('jar', Jar).configure { manifest { attributes([ 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors, 'Specification-Version' : '1', // We are version 1 of ourselves 'Implementation-Title' : project.name, 'Implementation-Version' : project.jar.archiveVersion, 'Implementation-Vendor' : mod_authors, 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"), "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "TweakOrder" : 0, "MixinConfigs" : "derp.mixin.json" ]) } rename 'mixin.refmap.json', 'derp.mixin-refmap.json' } shadowJar { archiveClassifier = '' configurations = [project.configurations.shade] finalizedBy 'reobfShadowJar' } assemble.dependsOn shadowJar reobf { re shadowJar {} } publishing { publications { mavenJava(MavenPublication) { artifact jar } } repositories { maven { url "file://${project.projectDir}/mcmodsrepo" } } } my entire project:https://github.com/kevin051606/DERP-Mod/tree/Derp-1.0-1.20
  • Topics

×
×
  • Create New...

Important Information

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