Java Code Examples for org.bukkit.util.Vector#length()

The following examples show how to use org.bukkit.util.Vector#length() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XParticle.java    From XSeries with MIT License 6 votes vote down vote up
/**
 * Spawns a line from a location to another.
 * Tutorial: https://www.spigotmc.org/threads/176695/
 *
 * @param start the starting point of the line.
 * @param end   the ending point of the line.
 * @param rate  the rate of points of the line.
 * @see #drawLine(Player, double, double, ParticleDisplay)
 * @since 1.0.0
 */
public static void line(Location start, Location end, double rate, ParticleDisplay display) {
    Vector distance = end.toVector().subtract(start.toVector());
    double length = distance.length();
    distance.normalize();

    double x = distance.getX();
    double y = distance.getY();
    double z = distance.getZ();

    ParticleDisplay clone = display.clone();
    clone.location = start;
    for (double i = 0; i < length; i += rate) {
        // Since the rate can be any number it's possible to get a higher number than
        // the length in the last loop.
        if (i > length) i = length;
        clone.spawn(x * i, y * i, z * i);
    }
}
 
Example 2
Source File: TargetHelper.java    From ActionHealth with MIT License 6 votes vote down vote up
/**
 * Checks whether or not the line between the two points is obstructed
 *
 * @param loc1 first location
 * @param loc2 second location
 * @return the location of obstruction or null if not obstructed
 */
public boolean isObstructed(Location loc1, Location loc2) {
    if (loc1.getX() == loc2.getX() && loc1.getY() == loc2.getY() && loc1.getZ() == loc2.getZ()) {
        return false;
    }
    Vector slope = loc2.clone().subtract(loc1).toVector();
    int steps = (int) (slope.length() * 4) + 1;
    slope.multiply(1.0 / steps);
    Location temp = loc1.clone();
    for (int i = 0; i < steps; i++) {
        temp.add(slope);
        if (temp.getBlock().getType().isSolid() && !temp.getBlock().getType().toString().contains("FENCE") && !temp.getBlock().getType().toString().contains("GLASS")) {
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: GunUtil.java    From QualityArmory with GNU General Public License v3.0 6 votes vote down vote up
public static double getTargetedSolidMaxDistance(Vector v, Location start, double maxDistance) {
	Location test = start.clone();
	Block previous = null;
	for (double i = 0; i < maxDistance; i += v.length()) {
		if (test.getBlock() == previous) {
			previous = test.getBlock();
			test.add(v);
			continue;
		}
		if (test.getBlock().getType() != Material.AIR) {
			if (isSolid(test.getBlock(), test))
				return start.distance(test);
		}
		previous = test.getBlock();
		test.add(v);
	}
	return maxDistance;
}
 
Example 4
Source File: NetherTerraFormEvents.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
private Location findAirSpawnLocation(Location location, Vector v, ProtectedCuboidRegion islandRegion) {
    // Searches in a cone for an air block
    Location lookAt = new Location(location.getWorld(),
            Math.round(location.getX() + v.getX()),
            Math.round(location.getY() + v.getY()),
            Math.round(location.getZ() + v.getZ()));
    while (v.length() < maxScan) {
        for (Location loc : getLocationsInPlane(lookAt, v)) {
            if (loc.getBlock().getType() == Material.AIR && isAdjacentToSolid(loc)
                    && isInIslandRegion(islandRegion, loc)) {
                return loc;
            }
        }
        double n = v.length();
        v.normalize().multiply(n+1);
    }
    return null;
}
 
Example 5
Source File: NetherTerraFormEvents.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
private List<Location> getLocationsInPlane(Location location, Vector v) {
    Location lookAt = new Location(location.getWorld(),
            Math.round(location.getX() + v.getX()),
            Math.round(location.getY() + v.getY()),
            Math.round(location.getZ() + v.getZ()));
    List<Location> locs = new ArrayList<>();
    boolean xFixed = Math.abs(v.getX()) > Math.abs(v.getZ());
    for (int r = 1; r <= v.length(); r++) {
        for (int dy = -r; dy <= r; dy++) {
            for (int dxz = -r; dxz <= r; dxz++) {
                if (xFixed) {
                    locs.add(lookAt.clone().add(0, dy, dxz));
                } else {
                    locs.add(lookAt.clone().add(dxz, dy, 0));
                }
            }
        }
    }
    Collections.shuffle(locs);
    locs = locs.subList(0, locs.size()/2); // Only try half
    return locs;
}
 
Example 6
Source File: ArcEffect.java    From EffectLib with MIT License 6 votes vote down vote up
@Override
public void onRun() {
    Location location = getLocation();
    Location target = getTarget();
    if (target == null) {
        cancel();
        return;
    }
    Vector link = target.toVector().subtract(location.toVector());
    float length = (float) link.length();
    float pitch = (float) (4 * height / Math.pow(length, 2));
    for (int i = 0; i < particles; i++) {
        Vector v = link.clone().normalize().multiply((float) length * i / particles);
        float x = ((float) i / particles) * length - length / 2;
        float y = (float) (-pitch * Math.pow(x, 2) + height);
        location.add(v).add(0, y, 0);
        display(particle, location);
        location.subtract(0, y, 0).subtract(v);

        step++;
    }
}
 
Example 7
Source File: Effects.java    From TabooLib with MIT License 5 votes vote down vote up
public static void buildLine(Location locA, Location locB, Consumer<Location> action, double interval) {
    Vector vectorAB = locB.clone().subtract(locA).toVector();
    double vectorLength = vectorAB.length();
    vectorAB.normalize();
    for (double i = 0; i < vectorLength; i += interval) {
        action.accept(locA.clone().add(vectorAB.clone().multiply(i)));
    }
}
 
Example 8
Source File: Inertia.java    From Hawk with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void check(MoveEvent e) {
    Player p = e.getPlayer();
    HawkPlayer pp = e.getHawkPlayer();
    Vector moveVector = new Vector(e.getTo().getX() - e.getFrom().getX(), 0, e.getTo().getZ() - e.getFrom().getZ());
    Vector prevVector = pp.getVelocity().clone().setY(0);
    double horizSpeedSquared = Math.pow(e.getTo().getX() - e.getFrom().getX(), 2) + Math.pow(e.getTo().getZ() - e.getFrom().getZ(), 2);
    double deltaAngle = MathPlus.angle(moveVector, prevVector);
    boolean onGround = e.isOnGround(); //um... is this safe?
    boolean wasOnGround = pp.isOnGround(); //um... is this safe?

    if (!AdjacentBlocks.blockNearbyIsSolid(e.getTo(), true) && !wasOnGround && !onGround && !e.hasAcceptedKnockback() && !e.isTouchingBlocks() &&
            !AdjacentBlocks.blockNearbyIsSolid(e.getTo().clone().add(0, 1, 0), true) && !pp.isFlying() && !p.isInsideVehicle()) {

        //setting up expected values
        double magnitudeThres;
        double prevSpeed = e.hasHitSlowdown() ? prevVector.length() * 0.6 : prevVector.length();
        if(AdjacentBlocks.blockAdjacentIsLiquid(e.getFrom()) || AdjacentBlocks.blockAdjacentIsLiquid(e.getFrom().clone().add(0, 1, 0))) {
            magnitudeThres = 0; //screw it
        }
        else {
            magnitudeThres = e.getFriction() * prevSpeed - 0.026001;
        }

        //angle check
        if (horizSpeedSquared > 0.05 && deltaAngle > 0.2) {
            punishAndTryRubberband(pp, e);

        //magnitude check
        } else if(prevVector.lengthSquared() > 0.01 && moveVector.length() < magnitudeThres) {
            punishAndTryRubberband(pp, e);
        }

        else {
            reward(pp);
        }
    }
}
 
Example 9
Source File: NetherTerraFormEvents.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
private Location findSolidSpawnLocation(Location location, Vector v, ProtectedCuboidRegion islandRegion) {
    // Searches in a cone for an air block
    while (v.length() < maxScan) {
        for (Location loc : getLocationsInPlane(location, v)) {
            if (loc.getBlock().getType() == Material.AIR
                    && loc.getBlock().getRelative(BlockFace.DOWN).getType().isSolid()
                    && isInIslandRegion(islandRegion, loc)) {
                return loc;
            }
        }
        double n = v.length();
        v.normalize().multiply(n+1);
    }
    return null;
}
 
Example 10
Source File: DiscoBallEffect.java    From EffectLib with MIT License 5 votes vote down vote up
public void onRun() {
    Location location = getLocation();
    //Lines
    int mL = RandomUtils.random.nextInt(maxLines - 2) + 2;
    for (int m = 0; m < mL * 2; m++) {
        double x = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
        double y = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
        double z = RandomUtils.random.nextInt(max - max * (-1)) + max * (-1);
        if (direction == Direction.DOWN) {
            y = RandomUtils.random.nextInt(max * 2 - max) + max;
        } else if (direction == Direction.UP) {
            y = RandomUtils.random.nextInt(max * (-1) - max * (-2)) + max * (-2);
        }
        Location target = location.clone().subtract(x, y, z);
        if (target == null) {
            cancel();
            return;
        }
        Vector link = target.toVector().subtract(location.toVector());
        float length = (float) link.length();
        link.normalize();

        float ratio = length / lineParticles;
        Vector v = link.multiply(ratio);
        Location loc = location.clone().subtract(v);
        for (int i = 0; i < lineParticles; i++) {
            loc.add(v);
            display(lineParticle, loc, lineColor);
        }
    }

    //Sphere
    for (int i = 0; i < sphereParticles; i++) {
        Vector vector = RandomUtils.getRandomVector().multiply(sphereRadius);
        location.add(vector);
        display(sphereParticle, location, sphereColor);
        location.subtract(vector);
    }
}
 
Example 11
Source File: RadiusBomb.java    From NBTEditor with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onExplode(Item item, Location location) {
	Vector locV = item.getLocation().toVector();
	for (Entity entity : item.getNearbyEntities(_radius, _radius, _radius)) {
		if (entity instanceof LivingEntity) {
			Vector delta = ((LivingEntity) entity).getEyeLocation().toVector().subtract(locV);
			double factor = 1 - delta.length()/_radius;
			if (factor > 0) {
				affectEntity(item, location, (LivingEntity) entity, delta, factor);
			}
		}
	}
}
 
Example 12
Source File: BlockDropsMatchModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This is not an event handler. It is called explicitly by BlockTransformListener after all event
 * handlers have been called.
 */
@SuppressWarnings("deprecation")
public void doBlockDrops(final BlockTransformEvent event) {
  if (!causesDrops(event.getCause())) {
    return;
  }

  final BlockDrops drops = event.getDrops();
  if (drops != null) {
    event.setCancelled(true);
    final BlockState oldState = event.getOldState();
    final BlockState newState = event.getNewState();
    final Block block = event.getOldState().getBlock();
    final int newTypeId = newState.getTypeId();
    final byte newData = newState.getRawData();

    block.setTypeIdAndData(newTypeId, newData, true);

    if (event.getCause() instanceof EntityExplodeEvent) {
      EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
      final float yield = explodeEvent.getYield();

      if (drops.fallChance != null
          && oldState.getType().isBlock()
          && oldState.getType() != Material.AIR
          && match.getRandom().nextFloat() < drops.fallChance) {

        FallingBlock fallingBlock =
            match
                .getWorld()
                .spawnFallingBlock(
                    block.getLocation(),
                    event.getOldState().getType(),
                    event.getOldState().getRawData());
        fallingBlock.setDropItem(false);

        if (drops.landChance != null && match.getRandom().nextFloat() >= drops.landChance) {
          this.fallingBlocksThatWillNotLand.add(fallingBlock);
        }

        Vector v = fallingBlock.getLocation().subtract(explodeEvent.getLocation()).toVector();
        double distance = v.length();
        v.normalize().multiply(BASE_FALL_SPEED * drops.fallSpeed / Math.max(1d, distance));

        // A very simple deflection model. Check for a solid
        // neighbor block and "bounce" the velocity off of it.
        Block west = block.getRelative(BlockFace.WEST);
        Block east = block.getRelative(BlockFace.EAST);
        Block down = block.getRelative(BlockFace.DOWN);
        Block up = block.getRelative(BlockFace.UP);
        Block north = block.getRelative(BlockFace.NORTH);
        Block south = block.getRelative(BlockFace.SOUTH);

        if ((v.getX() < 0 && west != null && west.getType().isSolid())
            || v.getX() > 0 && east != null && east.getType().isSolid()) {
          v.setX(-v.getX());
        }

        if ((v.getY() < 0 && down != null && down.getType().isSolid())
            || v.getY() > 0 && up != null && up.getType().isSolid()) {
          v.setY(-v.getY());
        }

        if ((v.getZ() < 0 && north != null && north.getType().isSolid())
            || v.getZ() > 0 && south != null && south.getType().isSolid()) {
          v.setZ(-v.getZ());
        }

        fallingBlock.setVelocity(v);
      }

      // Defer item drops so the explosion doesn't destroy them
      match
          .getExecutor(MatchScope.RUNNING)
          .execute(() -> dropItems(drops, newState.getLocation(), yield));
    } else {
      MatchPlayer player = ParticipantBlockTransformEvent.getParticipant(event);
      if (player == null
          || player.getBukkit().getGameMode()
              != GameMode.CREATIVE) { // Don't drop items in creative mode
        dropItems(drops, newState.getLocation(), 1d);
        dropExperience(drops, newState.getLocation());
      }
    }
  }
}
 
Example 13
Source File: FightAccuracy.java    From Hawk with GNU General Public License v3.0 4 votes vote down vote up
private void swingProcessor(ArmSwingEvent e) {
    UUID uuid = e.getPlayer().getUniqueId();
    if (!lastAttacked.containsKey(uuid))
        return;

    HawkPlayer att = e.getHawkPlayer();
    HawkPlayer victim = lastAttacked.get(uuid);
    if (victim == null)
        return;
    long lastSwingTick = swingTick.getOrDefault(uuid, 0L);

    //proceed if victim's invulnerability is gone
    //diff between current client tick and last swing tick should never be negative
    //a bypass for this IS possible, but you'd get caught by TickRate if you try to change your tickrate
    if (att.getCurrentTick() - lastSwingTick >= victim.getPlayer().getMaximumNoDamageTicks() / 2) {

        Map<UUID, FightData> accuracyToVictim = accuracy.getOrDefault(uuid, new HashMap<>());
        FightData fightData = accuracyToVictim.getOrDefault(victim.getUuid(), new FightData());
        fightData.swings++;
        accuracyToVictim.put(victim.getUuid(), fightData);

        accuracy.put(uuid, accuracyToVictim);
        swingTick.put(uuid, att.getCurrentTick());
    }

    Location attackerLoc = new Location(att.getWorld(), att.getPosition().getX(), att.getPosition().getY(), att.getPosition().getZ(), att.getYaw(), att.getPitch());
    Location victimLoc = new Location(victim.getWorld(), victim.getPosition().getX(), victim.getPosition().getY(), victim.getPosition().getZ(), victim.getYaw(), victim.getPitch());

    //determine how far the opponent has moved horizontally on local coordinates and compute required mouse precision
    if(!attackerLoc.getWorld().equals(victimLoc.getWorld()))
        return;
    Vector victimVelocity = victim.getVelocity().clone().setY(0);
    Vector attackerDirection = att.getPlayer().getLocation().getDirection().clone().setY(0);
    double localMovement = MathPlus.sin((float)MathPlus.angle(victimVelocity, attackerDirection)) * victimVelocity.length();
    if(Double.isNaN(localMovement))
        localMovement = 0D;
    double requiredPrecision = localMovement * attackerLoc.distance(victimLoc);
    double effort = this.effort.getOrDefault(uuid, 0D);

    if(DEBUG) {
        if(requiredPrecision >= MIN_PRECISION_THRESHOLD && effort < EFFORT_THRESHOLD && effort + 0.02 >= EFFORT_THRESHOLD) {
            att.getPlayer().sendMessage(ChatColor.GREEN + "You are now eligible to be checked by fightaccuracy because your opponent is moving significantly.");
        }
        else if(requiredPrecision < MIN_PRECISION_THRESHOLD && effort >= EFFORT_THRESHOLD && effort - 0.01 < EFFORT_THRESHOLD) {
            att.getPlayer().sendMessage(ChatColor.RED + "You are no longer eligible to be checked by fightaccuracy because your opponent is not moving enough.");
        }
    }

    if (requiredPrecision >= MIN_PRECISION_THRESHOLD) {
        //increase effort
        this.effort.put(uuid, Math.min(effort + 0.02, 1));
    } else {
        //decrease effort
        this.effort.put(uuid, Math.max(effort - 0.01, 0));
    }
}
 
Example 14
Source File: AimbotHeuristic.java    From Hawk with GNU General Public License v3.0 4 votes vote down vote up
private void processMove(MoveEvent e) {
    Player p = e.getPlayer();
    HawkPlayer pp = e.getHawkPlayer();
    UUID uuid = p.getUniqueId();

    List<Vector> lastMoves = mouseMoves.getOrDefault(uuid, new ArrayList<>());
    Vector mouseMove = new Vector(e.getTo().getYaw() - e.getFrom().getYaw(), e.getTo().getPitch() - e.getFrom().getPitch(), 0);

    lastMoves.add(mouseMove);
    //make size 1 bigger so that we can get the move before
    //the first move that we check
    if(lastMoves.size() > MOVES_PER_SAMPLE + 1) {
        lastMoves.remove(0);
    }
    mouseMoves.put(uuid, lastMoves);

    if(clickedXMovesBefore(MOVES_AFTER_HIT, pp)) {
        double minSpeed = Double.MAX_VALUE;
        double maxSpeed = 0D;
        double maxAngle = 0D;
        for(int i = 1; i < lastMoves.size(); i++) {
            Vector lastMouseMove = lastMoves.get(i - 1);
            Vector currMouseMove = lastMoves.get(i);
            double speed = currMouseMove.length();
            double lastSpeed = lastMouseMove.length();
            double angle = (lastSpeed != 0 && lastSpeed != 0) ? MathPlus.angle(lastMouseMove, currMouseMove) : 0D;
            if(Double.isNaN(angle))
                angle = 0D;
            maxSpeed = Math.max(speed, maxSpeed);
            minSpeed = Math.min(speed, minSpeed);
            maxAngle = Math.max(angle, maxAngle);

            //stutter
            if(maxSpeed - minSpeed > 4 && minSpeed < 0.01 && maxAngle < 0.1 && lastSpeed > 1) { //this lastSpeed check eliminates a false positive
                punishEm(pp, e);
            }
            //twitching or zig zags
            else if(speed > 20 && lastSpeed > 20 && angle > 2.86) {
                punishEm(pp, e);
            }
            //jump discontinuity
            else if(speed - lastSpeed < -30 && angle > 0.8) {
                punishEm(pp, e);
            }
            else {
                reward(pp);
            }
        }
    }
}
 
Example 15
Source File: BlockDropsMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This is not an event handler. It is called explicitly by BlockTransformListener
 * after all event handlers have been called.
 */
@SuppressWarnings("deprecation")
public void doBlockDrops(final BlockTransformEvent event) {
    if(!causesDrops(event.getCause())) {
        return;
    }

    final BlockDrops drops = event.getDrops();
    if(drops != null) {
        event.setCancelled(true);
        final BlockState oldState = event.getOldState();
        final BlockState newState = event.getNewState();
        final Block block = event.getOldState().getBlock();
        final int newTypeId = newState.getTypeId();
        final byte newData = newState.getRawData();

        block.setTypeIdAndData(newTypeId, newData, true);

        boolean explosion = false;
        MatchPlayer player = ParticipantBlockTransformEvent.getParticipant(event);

        if(event.getCause() instanceof EntityExplodeEvent) {
            EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
            explosion = true;

            if(drops.fallChance != null &&
               oldState.getType().isBlock() &&
               oldState.getType() != Material.AIR &&
               this.getMatch().getRandom().nextFloat() < drops.fallChance) {

                FallingBlock fallingBlock = event.getOldState().spawnFallingBlock();
                fallingBlock.setDropItem(false);

                if(drops.landChance != null && this.getMatch().getRandom().nextFloat() >= drops.landChance) {
                    this.fallingBlocksThatWillNotLand.add(fallingBlock);
                }

                Vector v = fallingBlock.getLocation().subtract(explodeEvent.getLocation()).toVector();
                double distance = v.length();
                v.normalize().multiply(BASE_FALL_SPEED * drops.fallSpeed / Math.max(1d, distance));

                // A very simple deflection model. Check for a solid
                // neighbor block and "bounce" the velocity off of it.
                Block west = block.getRelative(BlockFace.WEST);
                Block east = block.getRelative(BlockFace.EAST);
                Block down = block.getRelative(BlockFace.DOWN);
                Block up = block.getRelative(BlockFace.UP);
                Block north = block.getRelative(BlockFace.NORTH);
                Block south = block.getRelative(BlockFace.SOUTH);

                if((v.getX() < 0 && west != null && Materials.isColliding(west.getType())) ||
                    v.getX() > 0 && east != null && Materials.isColliding(east.getType())) {
                    v.setX(-v.getX());
                }

                if((v.getY() < 0 && down != null && Materials.isColliding(down.getType())) ||
                    v.getY() > 0 && up != null && Materials.isColliding(up.getType())) {
                    v.setY(-v.getY());
                }

                if((v.getZ() < 0 && north != null && Materials.isColliding(north.getType())) ||
                    v.getZ() > 0 && south != null && Materials.isColliding(south.getType())) {
                    v.setZ(-v.getZ());
                }

                fallingBlock.setVelocity(v);
            }
        }

        dropObjects(drops, player, newState.getLocation(), 1d, explosion);

    }
}
 
Example 16
Source File: ExprVectorLength.java    From Skript with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings({"unused", "null"})
public Double convert(Vector vector) {
	return vector.length();
}