Teleport Method Keeps Doubling My Coordinates(Spigot)

I’m trying to make a teleport wand that would teleport you one block forward, explode, and give you regeneration for 1 second but everytime I teleport it would double my coords for some reason. For example, I would go from the coordinates 383, 43, 256 to the coordinates 767, 86, 512. Does anyone know what is causing this?

Here’s my Class code:

package com.jason.sbitems.swords;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.potion.PotionEffectType;

public class AOTE implements Listener {
    @EventHandler
    public static void onPlayerInteract(PlayerInteractEvent e) {
        Player p = e.getPlayer();
        Material mat = e.getPlayer().getInventory().getItemInMainHand().getType();

        int x = p.getLocation().getBlockX();
        int y = p.getLocation().getBlockY();
        int z = p.getLocation().getBlockZ();
        Location a = p.getLocation().add(x + 1, y, z);

        if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) {
            if (mat == Material.STICK) {
                p.getWorld().createExplosion(p.getLocation(), 0f);
                p.teleport(a);
                p.addPotionEffect(PotionEffectType.REGENERATION.createEffect(20, 1));
            }
        }
    }
}

Answer

Your issue is that you have misunderstood how the add() method works with locations. You are adding the provided doubles to the current location and so you do not need to specify the coordinate again.

So to add 1 to the X coordinate, you would do so like

Location a = p.getLocation().add(1, 0, 0);

You are doubling their coordinates by adding them again. Except for the X coordinate, where you are adding the value again plus one.

A side note, if your goal is to teleport the player one block forward, adding to the X will not always result in ‘forward’, depending on where the player is looking. You could achieve that with something similar to:

Vector teleportTo = player.getLocation().getDirection().normalize().multiply(1);
player.teleport(player.getLocation().add(teleportTo));

This will allow them to be teleported into a block so you will of course need to perform your own checks and modifications.

Leave a Reply

Your email address will not be published. Required fields are marked *