Java Code Examples for org.bukkit.Location#add()

The following examples show how to use org.bukkit.Location#add() . 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: ConeEffect.java    From EffectLib with MIT License 6 votes vote down vote up
@Override
public void onRun() {
    Location location = getLocation();
    for (int x = 0; x < particles; x++) {
        if (step > particlesCone) {
            step = 0;
        }
        if (randomize && step == 0) {
            rotation = RandomUtils.getRandomAngle();
        }
        double angle = step * angularVelocity + rotation;
        float radius = step * radiusGrow;
        float length = step * lengthGrow;
        Vector v = new Vector(Math.cos(angle) * radius, length, Math.sin(angle) * radius);
        VectorUtils.rotateAroundAxisX(v, (location.getPitch() + 90) * MathUtils.degreesToRadians);
        VectorUtils.rotateAroundAxisY(v, -location.getYaw() * MathUtils.degreesToRadians);

        location.add(v);
        display(particle, location);
        location.subtract(v);
        step++;
    }
}
 
Example 2
Source File: StarEffect.java    From EffectLib with MIT License 6 votes vote down vote up
@Override
public void onRun() {
    Location location = getLocation();
    float radius = 3 * innerRadius / MathUtils.SQRT_3;
    for (int i = 0; i < spikesHalf * 2; i++) {
        double xRotation = i * Math.PI / spikesHalf;
        for (int x = 0; x < particles; x++) {
            double angle = 2 * Math.PI * x / particles;
            float height = RandomUtils.random.nextFloat() * spikeHeight;
            Vector v = new Vector(Math.cos(angle), 0, Math.sin(angle));
            v.multiply((spikeHeight - height) * radius / spikeHeight);
            v.setY(innerRadius + height);
            VectorUtils.rotateAroundAxisX(v, xRotation);
            location.add(v);
            display(particle, location);
            location.subtract(v);
            VectorUtils.rotateAroundAxisX(v, Math.PI);
            VectorUtils.rotateAroundAxisY(v, Math.PI / 2);
            location.add(v);
            display(particle, location);
            location.subtract(v);
        }
    }
}
 
Example 3
Source File: ChatConvIO.java    From BetonQuest with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Moves the player back a few blocks in the conversation's center
 * direction.
 *
 * @param event PlayerMoveEvent event, for extracting the necessary data
 */
private void moveBack(PlayerMoveEvent event) {
    // if the player is in other world (he teleported himself), teleport him
    // back to the center of the conversation
    if (!event.getTo().getWorld().equals(conv.getLocation().getWorld()) || event.getTo()
            .distance(conv.getLocation()) > Integer.valueOf(Config.getString("config.max_npc_distance")) * 2) {
        event.getPlayer().teleport(conv.getLocation());
        return;
    }
    // if not, then calculate the vector
    float yaw = event.getTo().getYaw();
    float pitch = event.getTo().getPitch();
    Vector vector = new Vector(conv.getLocation().getX() - event.getTo().getX(),
            conv.getLocation().getY() - event.getTo().getY(), conv.getLocation().getZ() - event.getTo().getZ());
    vector = vector.multiply(1 / vector.length());
    // and teleport him back using this vector
    Location newLocation = event.getTo().clone();
    newLocation.add(vector);
    newLocation.setPitch(pitch);
    newLocation.setYaw(yaw);
    event.getPlayer().teleport(newLocation);
    if (Config.getString("config.notify_pullback").equalsIgnoreCase("true")) {
        conv.sendMessage(Config.getMessage(Config.getLanguage(), "pullback"));
    }
}
 
Example 4
Source File: CannonExplosionProjectile.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
public void onHit() {
	
	int spread = 3;
	int[][] offset = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
	for (int i = 0; i < 4; i++) {
		int x = offset[i][0]*spread;
		int y = 0;
		int z = offset[i][1]*spread;
		
		Location location = new Location(loc.getWorld(), loc.getX(),loc.getY(), loc.getZ());
		location = location.add(x, y, z);
		
		launchExplodeFirework(location);
		//loc.getWorld().createExplosion(location, 1.0f, true);
		setFireAt(location, spread);
	}
	
	launchExplodeFirework(loc);
	//loc.getWorld().createExplosion(loc, 1.0f, true);
	damagePlayers(loc, splash);
	setFireAt(loc, spread);		
}
 
Example 5
Source File: SentinelUtilities.java    From Sentinel with MIT License 6 votes vote down vote up
/**
 * Traces a ray from a start to an end, returning the end of the ray (stopped early if there are solid blocks in the way).
 */
public static Location rayTrace(Location start, Location end) {
    double dSq = start.distanceSquared(end);
    if (dSq < 1) {
        if (end.getBlock().getType().isSolid()) {
            return start.clone();
        }
        return end.clone();
    }
    double dist = Math.sqrt(dSq);
    Vector move = end.toVector().subtract(start.toVector()).multiply(1.0 / dist);
    int iters = (int) Math.ceil(dist);
    Location cur = start.clone();
    Location next = cur.clone().add(move);
    for (int i = 0; i < iters; i++) {
        if (next.getBlock().getType().isSolid()) {
            return cur;
        }
        cur = cur.add(move);
        next = next.add(move);
    }
    return cur;
}
 
Example 6
Source File: GridEffect.java    From EffectLib with MIT License 5 votes vote down vote up
protected void addParticle(Location location, Vector v) {
    v.setZ(0);
    VectorUtils.rotateAroundAxisY(v, rotation);
    location.add(v);
    display(particle, location);
    location.subtract(v);
}
 
Example 7
Source File: Test.java    From Survival-Games with GNU General Public License v3.0 5 votes vote down vote up
public Location getYLocation(World w, int x, int y, int z){
	Location l = new Location(w,x,y,z);
	while(l.getBlock().getType().equals(Material.AIR)){
		l.add(0,-1,0);
	}
	return l.add(0,1,0);
}
 
Example 8
Source File: HelixEffect.java    From EffectLib with MIT License 5 votes vote down vote up
@Override
public void onRun() {
    Location location = getLocation();
    for (int i = 1; i <= strands; i++) {
        for (int j = 1; j <= particles; j++) {
            float ratio = (float) j / particles;
            double angle = curve * ratio * 2 * Math.PI / strands + (2 * Math.PI * i / strands) + rotation;
            double x = Math.cos(angle) * ratio * radius;
            double z = Math.sin(angle) * ratio * radius;
            location.add(x, 0, z);
            display(particle, location);
            location.subtract(x, 0, z);
        }
    }
}
 
Example 9
Source File: BlockListener.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
@EventHandler(priority = EventPriority.NORMAL)
public void onProjectileHitEvent(ProjectileHitEvent event) {
	if (event.getEntity() instanceof Arrow) {
		ArrowFiredCache afc = CivCache.arrowsFired.get(event.getEntity().getUniqueId());
		if (afc != null) {
			afc.setHit(true);
		}
	}

	if (event.getEntity() instanceof Fireball) {
		CannonFiredCache cfc = CivCache.cannonBallsFired.get(event.getEntity().getUniqueId());
		if (cfc != null) {

			cfc.setHit(true);

			FireworkEffect fe = FireworkEffect.builder().withColor(Color.RED).withColor(Color.BLACK).flicker(true).with(Type.BURST).build();

			Random rand = new Random();
			int spread = 30;
			for (int i = 0; i < 15; i++) {
				int x = rand.nextInt(spread) - spread/2;
				int y = rand.nextInt(spread) - spread/2;
				int z = rand.nextInt(spread) - spread/2;


				Location loc = event.getEntity().getLocation();
				Location location = new Location(loc.getWorld(), loc.getX(),loc.getY(), loc.getZ());
				location.add(x, y, z);

				TaskMaster.syncTask(new FireWorkTask(fe, loc.getWorld(), loc, 5), rand.nextInt(30));
			}

		}
	}
}
 
Example 10
Source File: Target.java    From Civs with GNU General Public License v3.0 5 votes vote down vote up
public Location applyTargetSettings(Location currentLocation) {
    //jitter
    int level = getLevel();
    HashMap<String, HashMap<Object, HashMap<String, Double>>> abilityVariables = getSpell().getAbilityVariables();
    String jitter = config.getString("jitter");
    if (jitter != null) {
        String jX = jitter.split(";")[0];
        String jY = jitter.split(";")[1];
        String jZ = jitter.split(";")[2];
        double jitterX = Spell.getLevelAdjustedValue(jX, level, null, null);
        double jitterY = Spell.getLevelAdjustedValue(jY, level, null, null);
        double jitterZ = Spell.getLevelAdjustedValue(jZ, level, null, null);

        if (jitterX != 0) {
            jitterX = Math.random() * jitterX * 2 - jitterX;
        }
        if (jitterY != 0) {
            jitterY = Math.random() * jitterY * 2 - jitterY;
        }
        if (jitterZ != 0) {
            jitterZ = Math.random() * jitterZ * 2 - jitterZ;
        }
        currentLocation = currentLocation.add(jitterX, jitterY, jitterZ);
    }
    //offset
    String offset = config.getString("offset");
    if (offset != null) {
        double offsetX = Spell.getLevelAdjustedValue(offset.split(";")[0], level, null, null);
        double offsetY = Spell.getLevelAdjustedValue(offset.split(";")[1], level, null, null);
        double offsetZ = Spell.getLevelAdjustedValue(offset.split(";")[2], level, null, null);
        currentLocation = currentLocation.add(offsetX, offsetY, offsetZ);
    }
    return currentLocation;
}
 
Example 11
Source File: SurgarCanePopulator.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void populate(World world, Random random, Chunk chunk){
    for (int x = 1; x < 15; x++) {
        for (int z = 1; z < 15; z++) {
            Block block = world.getHighestBlockAt(chunk.getBlock(x, 0, z).getLocation());
            Block below = block.getRelative(BlockFace.DOWN);

            if (percentage > random.nextInt(100) && (below.getType() == Material.SAND || below.getType() == Material.GRASS)){

                Material water = UniversalMaterial.STATIONARY_WATER.getType();
                if (
                        below.getRelative(BlockFace.NORTH).getType() == water ||
                        below.getRelative(BlockFace.EAST).getType() == water ||
                        below.getRelative(BlockFace.SOUTH).getType() == water ||
                        below.getRelative(BlockFace.WEST).getType() == water
                ){
                    if (block.getType() == Material.AIR){
                        int height = random.nextInt(3)+1;
                        Location location = block.getLocation();
                        while (height > 0){
                            world.getBlockAt(location).setType(UniversalMaterial.SUGAR_CANE_BLOCK.getType());
                            location = location.add(0, 1, 0);
                            height--;
                        }
                    }
                }
            }
        }
    }
}
 
Example 12
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 13
Source File: MusicEffect.java    From EffectLib with MIT License 5 votes vote down vote up
@Override
public void onRun() {
    Location location = getLocation();
    location.add(0, 1.9f, 0);
    location.add(Math.cos(radialsPerStep * step) * radius, 0, Math.sin(radialsPerStep * step) * radius);

    display(particle, location);
    step++;
}
 
Example 14
Source File: DnaEffect.java    From EffectLib with MIT License 5 votes vote down vote up
protected void drawParticle(Location location, Vector v, Particle particle, Color color) {
    VectorUtils.rotateAroundAxisX(v, (location.getPitch() + 90) * MathUtils.degreesToRadians);
    VectorUtils.rotateAroundAxisY(v, -location.getYaw() * MathUtils.degreesToRadians);

    location.add(v);
    display(particle, location, color);
    location.subtract(v);
}
 
Example 15
Source File: Timber.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
private void breakTree(Player player, ItemStack tool, Block block, List<Material> allowed, List<Location> locs) { //TODO: Improve algorithm and performance -> async?
	for (int dx = -1; dx <= 1; dx++) {
		for (int dy = -1; dy <= 1; dy++) {
			for (int dz = -1; dz <= 1; dz++) {
				if (dx == 0 && dy == 0 && dz == 0) {
					continue;
				}

				Location loc = block.getLocation().clone();
				loc.add(dx, dy, dz);

				if (locs.contains(loc)) {
					continue;
				}

				if (locs.size() >= maxBlocks) {
					return;
				}

				locs.add(loc);

				Block toBreak = player.getWorld().getBlockAt(loc);
				if (allowed.contains(toBreak.getType())) {
					breakTree(player, tool, toBreak, allowed, locs);
					DataHandler.playerBreakBlock(player, toBreak, tool);
				}
			}
		}
	}
}
 
Example 16
Source File: Bar.java    From AnnihilationPro with MIT License 4 votes vote down vote up
private Location getDragonLocation(Location loc)
{
    loc.add(0, -300, 0);
    return loc;
}
 
Example 17
Source File: Utils.java    From ArmorStandTools with MIT License 4 votes vote down vote up
static Block findAnAirBlock(Location l) {
    while(l.getY() < 255 && l.getBlock().getType() != Material.AIR) {
        l.add(0, 1, 0);
    }
    return l.getY() < 255 && l.getBlock().getType() == Material.AIR ? l.getBlock() : null;
}
 
Example 18
Source File: CombatLogTracker.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Get the cause of the player's imminent death, or null if they are not about to die NOTE: not
 * idempotent, has the side effect of clearing the recentDamage cache
 */
public @Nullable ImminentDeath getImminentDeath(Player player) {
  // If the player is already dead or in creative mode, we don't care
  if (player.isDead() || player.getGameMode() == GameMode.CREATIVE) return null;

  // If the player was on the ground, or is flying, or is able to fly, they are fine
  if (!(player.isOnGround() || player.isFlying() || player.getAllowFlight())) {
    // If the player is falling, detect an imminent falling death
    double fallDistance = player.getFallDistance();
    Block landingBlock = null;
    int waterDepth = 0;
    Location location = player.getLocation();

    if (location.getY() > 256) {
      // If player is above Y 256, assume they fell at least to there
      fallDistance += location.getY() - 256;
      location.setY(256);
    }

    // Search the blocks directly beneath the player until we find what they would have landed on
    Block block = null;
    for (; location.getY() >= 0; location.add(0, -1, 0)) {
      block = location.getBlock();
      if (block != null) {
        landingBlock = block;

        if (Materials.isWater(landingBlock.getType())) {
          // If the player falls through water, reset fall distance and inc the water depth
          fallDistance = -1;
          waterDepth += 1;

          // Break if they have fallen through enough water to stop falling
          if (waterDepth >= BREAK_FALL_WATER_DEPTH) break;
        } else {
          // If the block is not water, reset the water depth
          waterDepth = 0;

          if (Materials.isSolid(landingBlock.getType())
              || Materials.isLava(landingBlock.getType())) {
            // Break if the player hits a solid block or lava
            break;
          } else if (landingBlock.getType() == Material.WEB) {
            // If they hit web, reset their fall distance, but assume they keep falling
            fallDistance = -1;
          }
        }
      }

      fallDistance += 1;
    }

    double resistanceFactor = getResistanceFactor(player);
    boolean fireResistance = hasFireResistance(player);

    // Now decide if the landing would have killed them
    if (location.getBlockY() < 0) {
      // The player would have fallen into the void
      return new ImminentDeath(EntityDamageEvent.DamageCause.VOID, location, null, false);
    } else if (landingBlock != null) {
      if (Materials.isSolid(landingBlock.getType())
          && player.getHealth() <= resistanceFactor * (fallDistance - SAFE_FALL_DISTANCE)) {
        // The player would have landed on a solid block and taken enough fall damage to kill them
        return new ImminentDeath(
            EntityDamageEvent.DamageCause.FALL,
            landingBlock.getLocation().add(0, 0.5, 0),
            null,
            false);
      } else if (Materials.isLava(landingBlock.getType())
          && resistanceFactor > 0
          && !fireResistance) {
        // The player would have landed in lava, and we give the lava the benefit of the doubt
        return new ImminentDeath(
            EntityDamageEvent.DamageCause.LAVA, landingBlock.getLocation(), landingBlock, false);
      }
    }
  }

  // If we didn't predict a falling death, detect combat log due to recent damage
  Damage damage = this.recentDamage.remove(player);
  if (damage != null && damage.time.plus(RECENT_DAMAGE_THRESHOLD).isAfter(Instant.now())) {
    // Player logged out too soon after taking damage
    return new ImminentDeath(damage.event.getCause(), player.getLocation(), null, true);
  }

  return null;
}
 
Example 19
Source File: SitListener.java    From NyaaUtils with MIT License 4 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onClickBlock(PlayerInteractEvent event) {
    if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && !event.hasItem()) {
        Block block = event.getClickedBlock();
        BlockFace face = event.getBlockFace();
        if (face == BlockFace.DOWN || block.isLiquid() || !plugin.cfg.sit_blocks.contains(block.getType())) {
            return;
        }
        Block relative = block.getRelative(0, 1, 0);
        Player player = event.getPlayer();
        if (messageCooldown.getIfPresent(player.getUniqueId()) != null) {
            return;
        }
        messageCooldown.put(player.getUniqueId(), true);
        if (!player.hasPermission("nu.sit") || !enabledPlayers.contains(player.getUniqueId()) || player.isInsideVehicle() || !player.getPassengers().isEmpty() || player.getGameMode() == GameMode.SPECTATOR || !player.isOnGround()) {
            return;
        }
        if (relative.isLiquid() || !(relative.isEmpty() || relative.isPassable())) {
            player.sendMessage(I18n.format("user.sit.invalid_location"));
            return;
        }
        Vector vector = block.getBoundingBox().getCenter().clone();
        Location loc = vector.setY(block.getBoundingBox().getMaxY()).toLocation(player.getWorld()).clone();
        for (SitLocation sl : plugin.cfg.sit_locations.values()) {
            if (sl.blocks != null && sl.x != null && sl.y != null && sl.z != null && sl.blocks.contains(block.getType().name())) {
                loc.add(sl.x, sl.y, sl.z);
            }
        }
        if (block.getBlockData() instanceof Directional) {
            face = ((Directional) block.getBlockData()).getFacing();
            if (face == BlockFace.EAST) {
                loc.setYaw(90);
            } else if (face == BlockFace.WEST) {
                loc.setYaw(-90);
            } else if (face == BlockFace.NORTH) {
                loc.setYaw(0);
            } else if (face == BlockFace.SOUTH) {
                loc.setYaw(-180);
            }
        } else {
            if (face == BlockFace.WEST) {
                loc.setYaw(90);
            } else if (face == BlockFace.EAST) {
                loc.setYaw(-90);
            } else if (face == BlockFace.SOUTH) {
                loc.setYaw(0);
            } else if (face == BlockFace.NORTH) {
                loc.setYaw(-180);
            } else {
                loc.setYaw(player.getEyeLocation().getYaw());
            }
        }
        for (Entity e : loc.getWorld().getNearbyEntities(loc, 0.5, 0.7, 0.5)) {
            if (e instanceof LivingEntity) {
                if (e.hasMetadata(metadata_key) || (e instanceof Player && e.isInsideVehicle() && e.getVehicle().hasMetadata(metadata_key))) {
                    player.sendMessage(I18n.format("user.sit.invalid_location"));
                    return;
                }
            }
        }
        Location safeLoc = player.getLocation().clone();
        ArmorStand armorStand = loc.getWorld().spawn(loc, ArmorStand.class, (e) -> {
            e.setVisible(false);
            e.setPersistent(false);
            e.setCanPickupItems(false);
            e.setBasePlate(false);
            e.setArms(false);
            e.setMarker(true);
            e.setInvulnerable(true);
            e.setGravity(false);
        });
        if (armorStand != null) {
            armorStand.setMetadata(metadata_key, new FixedMetadataValue(plugin, true));
            if (armorStand.addPassenger(player)) {
                safeLocations.put(player.getUniqueId(), safeLoc);
            } else {
                armorStand.remove();
            }
        }
    }
}
 
Example 20
Source File: Utils.java    From BedwarsRel with GNU General Public License v3.0 4 votes vote down vote up
public static Location getDirectionLocation(Location location, int blockOffset) {
  Location loc = location.clone();
  return loc.add(loc.getDirection().setY(0).normalize().multiply(blockOffset));
}