Exemplo n.º 1
0
  @Override
  protected void magicSpellTriggered(RaCPlayer player, TraitResults result) {
    LivingEntity pushbackEntity = SearchEntity.inLineOfSight(30, player.getPlayer());

    if (pushbackEntity != null && EnemyChecker.areEnemies(player.getPlayer(), pushbackEntity)) {

      String targetName =
          pushbackEntity.getType() == EntityType.PLAYER
              ? ((Player) pushbackEntity).getName()
              : pushbackEntity.getType().name();

      LanguageAPI.sendTranslatedMessage(player, Keys.trait_pushaway_success, "target", targetName);

      Vector playerVector = player.getLocation().getDirection();
      if (up) {
        playerVector.copy(new Vector());
        playerVector.setY(blocks);
      } else {
        playerVector.setY(0);
        playerVector.multiply(this.blocks);
        playerVector.setY(0.2);
      }

      if (targetParticles != null)
        Vollotile.get().sendOwnParticleEffectToAll(targetParticles, pushbackEntity.getLocation());
      pushbackEntity.setVelocity(playerVector);

      result.setTriggered(true);
      return;
    }

    result.setTriggered(false);
    return;
  }
Exemplo n.º 2
0
  @Override
  public void progress() {
    if (!bPlayer.canBendIgnoreBindsCooldowns(this)) {
      remove();
      return;
    }

    getFloor();
    if (floorblock == null) {
      remove();
      return;
    }

    Vector velocity = player.getEyeLocation().getDirection().clone();
    velocity.setY(0);
    velocity = velocity.clone().normalize().multiply(speed);

    if (System.currentTimeMillis() > startTime + interval) {
      if (player.getVelocity().length() < speed * .5) {
        remove();
        return;
      }
      spinScooter();
    }

    double distance = player.getLocation().getY() - (double) floorblock.getY();
    double dx = Math.abs(distance - 2.4);
    if (distance > 2.75) {
      velocity.setY(-.25 * dx * dx);
    } else if (distance < 2) {
      velocity.setY(.25 * dx * dx);
    } else {
      velocity.setY(0);
    }

    Location loc = player.getLocation();
    if (!WaterAbility.isWater(player.getLocation().add(0, 2, 0).getBlock())) {
      loc.setY((double) floorblock.getY() + 1.5);
    } else {
      return;
    }

    player.setSprinting(false);
    player.removePotionEffect(PotionEffectType.SPEED);
    player.setVelocity(velocity);
    if (random.nextInt(4) == 0) {
      playAirbendingSound(player.getLocation());
    }
  }
Exemplo n.º 3
0
  @Override
  public boolean onDamageOther(EntityDamageByEntityEvent e, Player p, int level) {
    if (e.getEntity() instanceof LivingEntity) {
      LivingEntity le = (LivingEntity) e.getEntity();

      try {
        fireworks.playFirework(
            le.getWorld(),
            le.getLocation(),
            FireworkEffect.builder().with(Type.BURST).withColor(Color.WHITE).build());
      } catch (Exception ex) {
        Logger.getLogger(Burst.class.getName()).log(Level.SEVERE, null, ex);
      }

      Vector unitVector =
          le.getLocation().toVector().subtract(e.getDamager().getLocation().toVector()).normalize();

      unitVector.setY(0.55 / level);

      le.setVelocity(unitVector.multiply(level * 2));

      e.setCancelled(true);

      return true;
    }
    return false;
  }
Exemplo n.º 4
0
  public void bOOM() {
    Vector v = p.getVelocity();
    v.setY(2.3);
    p.teleport(p.getLocation().add(0, 0.5, 0));
    p.setVelocity(v);
    p.setFallDistance(0F);
    TempData.sonicRainBoomMap.put(p.getUniqueId(), System.currentTimeMillis());
    p.sendMessage(ChatColor.LIGHT_PURPLE + "SONIC RAINBOOM!");
    TempData.fallMap.add(p.getUniqueId());

    // Particles
    final World world = p.getWorld();

    for (int i = 0; i < 20 * 4; i++) {
      Bukkit.getScheduler()
          .scheduleSyncDelayedTask(
              Main.PLUGIN,
              new Runnable() {

                @Override
                public void run() {

                  world
                      .spigot()
                      .playEffect(p.getLocation(), Effect.COLOURED_DUST, 1, 1, 1, 1, 1, 1, 48, 30);
                }
              },
              i);
    }
  }
Exemplo n.º 5
0
  public static Vector calculateVector(Location loc) {

    Vector vec = loc.getDirection();
    int mult = 3;
    vec.setX(vec.getX() * mult);
    vec.setY(vec.getY() * mult);
    vec.setZ(vec.getZ() * mult);
    return vec;
  }
Exemplo n.º 6
0
  private void tossItem(ItemStack dropItem) {
    Location loc = player.getLocation();
    loc.setY(loc.getY() + 1);

    Item item = loc.getWorld().dropItem(loc, dropItem);
    Vector v = loc.getDirection().multiply(0.2);
    v.setY(0.2);
    item.setVelocity(v);
  }
Exemplo n.º 7
0
 @Override
 public void onRun() {
   Location location = getLocation();
   for (int i = 0; i < particles; i++) {
     Vector vector = RandomUtils.getRandomVector().multiply(radius);
     if (!sphere) vector.setY(Math.abs(vector.getY()));
     location.add(vector);
     particle.display(location, visibleRange);
     location.subtract(vector);
   }
 }
Exemplo n.º 8
0
  @EventHandler
  public void LocationUpdater(UpdateEvent event) {
    if (event.getType() == UpdateType.TICK) {
      for (Player p : EffectManager.effect3.keySet()) {
        if (EffectManager.getEffect(p) == EffectManager.EffectType.HourGlass) {
          if (p.isValid()) {
            if (ExtraManager.isMoving(p)) {
              Location location = p.getLocation();

              Vector vector = new Vector();

              for (int i = 0; i < this.particlesPerIteration; i++) {
                this.step += 1;

                float t = 3.141593F / this.particles * this.step;
                float r =
                    MathUtils.sin(t * 2.718282F * this.particlesPerIteration / this.particles)
                        * this.size;
                float s = r * 3.141593F * t;

                vector.setX(this.xFactor * r * -MathUtils.cos(s));
                vector.setZ(this.zFactor * r * -MathUtils.sin(s));
                vector.setY(this.yFactor * r + this.yOffset + 2.0F);

                UtilVector.rotateVector(vector, this.xRotation, this.yRotation, this.zRotation);
                ParticleLib18 ench =
                    new ParticleLib18(
                        com.lightcraftmc.particles18.ParticleLib18.ParticleType.ENCHANTMENT_TABLE,
                        0.0D,
                        1,
                        0.0D);
                ench.sendToLocation(location.add(vector));

                location.subtract(vector);
              }

            } else if (!p.isInsideVehicle()) {
              ParticleLib18 ench2 =
                  new ParticleLib18(
                      com.lightcraftmc.particles18.ParticleLib18.ParticleType.ENCHANTMENT_TABLE,
                      0.1000000014901161D,
                      4,
                      0.300000011920929D);
              ench2.sendToLocation(p.getLocation().add(0.0D, 1.0D, 0.0D));
            }
          }
        }
      }
    }
  }
Exemplo n.º 9
0
  @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
  public void EntityDamageEvent(EntityDamageEvent e) {

    Entity damaged = e.getEntity();

    if (damaged instanceof Player) {

      CEventHandler.handleEvent((Player) damaged, e, damageNature);

      if (damaged.hasMetadata("ce.springs")) {
        e.setCancelled(true);
        Vector vel = damaged.getVelocity();
        vel.setY((vel.getY() * -0.75) > 1 ? vel.getY() * -0.75 : 0);
        damaged.setVelocity(vel);
      }
    }
  }
Exemplo n.º 10
0
 @Override
 public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
   if (cmd.getName().equalsIgnoreCase("slap")) {
     if (!plugin.isAuthorized(cs, "rcmds.slap")) {
       RUtils.dispNoPerms(cs);
       return true;
     }
     if (args.length < 1) {
       cs.sendMessage(cmd.getDescription());
       return false;
     }
     Player victim;
     victim = plugin.getServer().getPlayer(args[0]);
     if (victim == null || plugin.isVanished(victim)) {
       cs.sendMessage(ChatColor.RED + "That person is not online!");
       return true;
     }
     if (plugin.isAuthorized(victim, "rcmds.exempt.slap")) {
       cs.sendMessage(ChatColor.RED + "You may not slap that player.");
       return true;
     }
     Vector push = victim.getVelocity();
     push.setY(push.getY() + .5);
     push.setX(push.getX() + .5);
     push.setZ(push.getZ() + .5);
     victim.setVelocity(push);
     plugin
         .getServer()
         .broadcastMessage(
             ChatColor.GOLD
                 + cs.getName()
                 + ChatColor.WHITE
                 + " slaps "
                 + ChatColor.RED
                 + victim.getName()
                 + ChatColor.WHITE
                 + "!");
     return true;
   }
   return false;
 }
  /**
   * Find a suitable location for a player to teleport to in the given world. This method uses
   * WorldBorder as the configuration source.
   *
   * @param world World to teleport to
   * @return Location to teleport to
   */
  private Location findSuitableLocationWB(World world) {
    BorderData borderData = WorldBorder.plugin.GetWorldBorder(world.getName());

    if (borderData == null) {
      // throw new IllegalStateException(String.format("World %1$s isn't configured in
      // WorldBorder.", world.getName()));
      return null;
    }

    for (int i = 0; i < 100; i++) {
      Vector position = new Vector(borderData.getX(), 0.0, borderData.getZ());

      // Get a uniform-area random position within the world border's geometry
      boolean isRound = (borderData.getShape() == null) ? true : borderData.getShape();
      if (isRound) {
        position.add(
            getRandomPointInEllipse(random, borderData.getRadiusX(), borderData.getRadiusZ()));
      } else {
        position.add(
            getRandomPointInRectangle(random, borderData.getRadiusX(), borderData.getRadiusZ()));
      }

      // Ensure there's a solid block to stand on
      Block highestBlock = world.getHighestBlockAt(position.getBlockX(), position.getBlockZ());
      if (highestBlock == null) continue;
      highestBlock = highestBlock.getRelative(0, -1, 0); // Because the javadocs are wrong.
      if (highestBlock == null) continue;
      if (highestBlock.getY() < 1 || highestBlock.getY() >= world.getMaxHeight() - 2) continue;
      if (highestBlock.isLiquid()) continue;

      position.setX((double) position.getBlockX() + 0.5);
      position.setY(highestBlock.getY() + 2);
      position.setZ((double) position.getBlockZ() + 0.5);

      return position.toLocation(world, getRandomYaw(), 0.0f);
    }

    return null;
  }
  @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
  public void onPlayerMove(PlayerMoveEvent event) {
    Player player = event.getPlayer();
    if (Concussion.getTarget(player) != null) {
      event.setCancelled(true);
      return;
    }
    if (WaterSpout.isBending(event.getPlayer())
        || AirSpout.getPlayers().contains(event.getPlayer())) {
      Vector vel = new Vector();
      vel.setX(event.getTo().getX() - event.getFrom().getX());
      vel.setY(event.getTo().getY() - event.getFrom().getY());
      vel.setZ(event.getTo().getZ() - event.getFrom().getZ());
      // You now know the old velocity. Set to match recommended velocity
      double currspeed = vel.length();
      double maxspeed = .15;
      if (currspeed > maxspeed) {
        vel = vel.normalize().multiply(maxspeed * 0.9);
        event.getPlayer().setVelocity(vel);
      }
    }
    if (Bloodbending.isBloodbended(player)) {
      double distance1, distance2;
      Location loc = Bloodbending.getBloodbendingLocation(player);
      distance1 = event.getFrom().distance(loc);
      distance2 = event.getTo().distance(loc);
      if (distance2 > distance1) {
        player.setVelocity(new Vector(0, 0, 0));
      }
    }

    if (Dash.isDashing(player)) {
      Vector dir = event.getTo().clone().subtract(event.getFrom()).toVector();
      Dash d = Dash.getDash(player);
      d.setDirection(dir);
    }
  }
Exemplo n.º 13
0
  private void affect(Entity entity) {
    BendingHitEvent event = new BendingHitEvent(ability, entity);
    Bending.callEvent(event);
    if (event.isCancelled()) {
      return;
    }

    double damage = DAMAGE;
    if (bender.hasPath(BendingPath.TOUGH)) {
      damage *= 0.85;
    }

    if (bender.hasPath(BendingPath.RECKLESS)) {
      damage *= 1.15;
    }

    if (entity instanceof LivingEntity) {
      DamageTools.damageEntity(bender, entity, ability, damage);
    }

    Vector vector = direction.clone();
    vector.setY(.5);
    entity.setVelocity(vector);
  }
Exemplo n.º 14
0
  private void getBlocking(EnderPearl pearl) {
    double gravity = 0.03F;
    try {
      if (pearl instanceof CustomNMSEntityEnderPearl)
        gravity = ((CustomNMSEntityEnderPearl) pearl).y_adjust_;
      else Bastion.getPlugin().getLogger().info("Humbug not found");

    } catch (NoClassDefFoundError e) {
      Bastion.getPlugin().getLogger().info("Humbug not found");
    }

    Vector speed = pearl.getVelocity();
    Vector twoDSpeed = speed.clone();
    twoDSpeed.setY(0);

    double horizontalSpeed = getLengthSigned(twoDSpeed);
    double verticalSpeed = speed.getY();

    Location loc = pearl.getLocation();

    double maxTicks = getMaxTicks(verticalSpeed, loc.getY(), -gravity);
    double maxDistance = getMaxDistance(horizontalSpeed, maxTicks);

    // check if it has any possibility of going through a bastion
    if (!(maxDistance > Bastion.getConfigManager().getBastionBlockEffectRadius() / 2
        || maxDistance < -1)) {
      return;
    }

    Player threw = null;
    if (pearl.getShooter() instanceof Player) {
      threw = (Player) pearl.getShooter();
    }

    Set<BastionBlock> possible =
        bastions.getPossibleTeleportBlocking(
            pearl.getLocation(), maxDistance); // all the bastion blocks within range of the pearl

    // no need to do anything if there aren't any bastions to run into.
    if (possible.isEmpty()) {
      return;
    }

    Location start = pearl.getLocation();
    Location end = start.clone();
    end.add(twoDSpeed.multiply(maxTicks));

    Set<BastionBlock> couldCollide =
        simpleCollide(
            possible,
            start.clone(),
            end.clone(),
            threw); // all the bastions where the pearl passes over or under their shadow

    if (couldCollide.isEmpty()) {
      return;
    }

    BastionBlock firstCollision = null;
    long firstCollisionTime = -1;
    for (BastionBlock bastion : couldCollide) {
      long currentCollidesBy =
          (long) collidesBy(bastion, start.clone(), end.clone(), speed, gravity, horizontalSpeed);
      if (currentCollidesBy != -1 && currentCollidesBy < firstCollisionTime) {
        firstCollisionTime = currentCollidesBy;
        firstCollision = bastion;
      }

      // make sure there is at least a starting value Probably better ways of doing this
      if (firstCollisionTime == -1 && currentCollidesBy != -1) {
        firstCollisionTime = currentCollidesBy;
        firstCollision = bastion;
      }
    }
    if (firstCollisionTime != -1) { // if we found something add it
      task.manage(new Flight(pearl, firstCollisionTime, firstCollision));
      return;
    }
  }
Exemplo n.º 15
0
  @Override
  public void run() {
    for (Location l : Storage.blackholes.keySet()) {
      for (Entity e : Utilities.getNearbyEntities(l, 10, 10, 10)) {
        if (e instanceof Player) {
          if (((Player) e).getGameMode().equals(CREATIVE)) {
            continue;
          }
        }
        if (Storage.blackholes.get(l)) {
          Vector v = l.clone().subtract(e.getLocation()).toVector();
          v.setX(v.getX() + (-.5f + Storage.rnd.nextFloat()) * 10);
          v.setY(v.getY() + (-.5f + Storage.rnd.nextFloat()) * 10);
          v.setZ(v.getZ() + (-.5f + Storage.rnd.nextFloat()) * 10);
          e.setVelocity(v.multiply(.35f));
          e.setFallDistance(0);
        } else {
          Vector v = e.getLocation().subtract(l.clone()).toVector();
          v.setX(v.getX() + (-.5f + Storage.rnd.nextFloat()) * 2);
          v.setY(v.getY() + Storage.rnd.nextFloat());
          v.setZ(v.getZ() + (-.5f + Storage.rnd.nextFloat()) * 2);
          e.setVelocity(v.multiply(.35f));
        }
      }
    }
    // Arrows
    toRemove.clear();
    for (Set<CustomArrow> pro : Storage.advancedProjectiles.values()) {
      for (CustomArrow a : pro) {
        a.onFlight();
        a.tick++;
        if (a.entity.isDead() || a.tick > 600) {
          toRemove.add(a);
        }
      }
    }
    for (CustomArrow pro : toRemove) {
      Storage.advancedProjectiles.remove(pro.entity);
      pro.entity.remove();
    }
    for (Block block : Storage.webs) {
      if (Storage.rnd.nextInt(175) == 0 && block.getChunk().isLoaded()) {
        block.setType(AIR);
        websToRemove.add(block);
      }
    }
    for (Block block : websToRemove) {
      Storage.webs.remove(block);
    }
    websToRemove.clear();
    for (LivingEntity ent : Storage.derpingEntities) {
      Location loc = ent.getLocation();
      loc.setYaw(Storage.rnd.nextFloat() * 360F);
      loc.setPitch(Storage.rnd.nextFloat() * 180F - 90F);
      ent.teleport(loc);
    }
    tick++;
    // Other stuff
    for (FallingBlock b : Storage.anthMobs2) {
      if (!Storage.anthVortex.contains(Storage.anthMobs.get(b))) {
        for (Entity e : b.getNearbyEntities(7, 7, 7)) {
          if (e instanceof LivingEntity) {
            LivingEntity lE = (LivingEntity) e;
            if (!(lE instanceof Player) && lE instanceof Monster) {
              b.setVelocity(e.getLocation().subtract(b.getLocation()).toVector().multiply(.25));
              if (lE.getLocation().getWorld().equals(b.getLocation().getWorld())) {
                if (lE.getLocation().distance(b.getLocation()) < 1.2) {
                  EntityDamageEvent evt =
                      new EntityDamageEvent(lE, EntityDamageEvent.DamageCause.SUFFOCATION, 100);
                  Bukkit.getPluginManager().callEvent(evt);
                  lE.setLastDamageCause(evt);
                  if (!evt.isCancelled()) {
                    lE.damage(8f);
                  }
                }
              }
            }
          }
        }
      }
    }
    boolean r = Storage.fallBool;
    Storage.fallBool = !Storage.fallBool;
    for (FallingBlock b : Storage.anthMobs.keySet()) {
      if (Storage.anthVortex.contains(Storage.anthMobs.get(b))) {
        Location loc = Storage.anthMobs.get(b).getLocation();
        Vector v;
        if (b.getLocation().getWorld().equals(Storage.anthMobs.get(b).getLocation().getWorld())) {
          if (r && b.getLocation().distance(Storage.anthMobs.get(b).getLocation()) < 10) {
            v = b.getLocation().subtract(loc).toVector();
          } else {
            int x = Storage.rnd.nextInt(12) - 6;
            int z = Storage.rnd.nextInt(12) - 6;
            Location tLoc = loc.clone();
            tLoc.setX(tLoc.getX() + x);
            tLoc.setZ(tLoc.getZ() + z);
            v = tLoc.subtract(b.getLocation()).toVector();
          }
          v.multiply(.05);
          boolean close = false;
          for (int x = -3; x < 0; x++) {
            if (b.getLocation().getBlock().getRelative(0, x, 0).getType() != AIR) {
              close = true;
            }
          }
          if (close) {
            v.setY(5);
          } else {
            v.setY(-.1);
          }
          b.setVelocity(v);
        }
      }
    }

    for (Arrow e : Storage.tracer.keySet()) {
      Entity close = null;
      double distance = 100;
      int level = Storage.tracer.get(e);
      level = level + 2;
      for (Entity e1 : e.getNearbyEntities(level, level, level)) {
        if (e1.getLocation().getWorld().equals(e.getLocation().getWorld())) {
          double d = e1.getLocation().distance(e.getLocation());
          if (e.getLocation()
              .getWorld()
              .equals(((Entity) e.getShooter()).getLocation().getWorld())) {
            if (d < distance
                && e1 instanceof LivingEntity
                && !e1.equals(e.getShooter())
                && e.getLocation().distance(((Entity) e.getShooter()).getLocation()) > 15) {
              distance = d;
              close = e1;
            }
          }
        }
      }
      if (close != null) {
        Location location = close.getLocation();
        org.bukkit.util.Vector v = new org.bukkit.util.Vector(0D, 0D, 0D);
        Location pos = e.getLocation();
        double its =
            Math.sqrt(
                (location.getBlockX() - pos.getBlockX()) * (location.getBlockX() - pos.getBlockX())
                    + (location.getBlockY() - pos.getBlockY())
                        * (location.getBlockY() - pos.getBlockY())
                    + (location.getBlockZ() - pos.getBlockZ())
                        * (location.getBlockZ() - pos.getBlockZ()));
        if (its == 0) {
          its = (double) 1;
        }
        v.setX((location.getBlockX() - pos.getBlockX()) / its);
        v.setY((location.getBlockY() - pos.getBlockY()) / its);
        v.setZ((location.getBlockZ() - pos.getBlockZ()) / its);
        e.setVelocity(v.multiply(2));
      }
    }

    for (Guardian g : Storage.guardianMove.keySet()) {
      if (g.getLocation().distance(Storage.guardianMove.get(g).getLocation()) > 2
          && g.getTicksLived() < 160) {
        g.setVelocity(
            Storage.guardianMove
                .get(g)
                .getLocation()
                .toVector()
                .subtract(g.getLocation().toVector()));
      } else {
        Storage.guardianMove.remove(g);
      }
    }

    for (Player player : Bukkit.getOnlinePlayers()) {
      Config config = Config.get(player.getWorld());
      for (ItemStack stk : player.getInventory().getArmorContents()) {
        HashMap<CustomEnchantment, Integer> map = config.getEnchants(stk);
        for (CustomEnchantment ench : map.keySet()) {
          ench.onFastScan(player, map.get(ench));
        }
      }
      HashMap<CustomEnchantment, Integer> map = config.getEnchants(player.getItemInHand());
      for (CustomEnchantment ench : map.keySet()) {
        ench.onFastScanHand(player, map.get(ench));
      }
    }
    HashSet<Player> toDelete = new HashSet<>();
    for (Player player : Storage.hungerPlayers.keySet()) {
      if (Storage.hungerPlayers.get(player) < 1) {
        toDelete.add(player);
      } else {
        Storage.hungerPlayers.put(player, Storage.hungerPlayers.get(player) - 1);
      }
    }
    for (Player p : toDelete) {
      Storage.hungerPlayers.remove(p);
    }
    toDelete.clear();
    for (Player player : Storage.moverBlockDecay.keySet()) {
      Storage.moverBlockDecay.put(player, Storage.moverBlockDecay.get(player) + 1);
      if (Storage.moverBlockDecay.get(player) > 5) {
        Storage.moverBlocks.remove(player);
        toDelete.add(player);
      }
    }
    for (Player p : toDelete) {
      Storage.moverBlockDecay.remove(p);
    }
  }
Exemplo n.º 16
0
  public SearchParser(CommandSender player, List<String> args) throws IllegalArgumentException {
    this.player = player;

    String lastParam = "";
    boolean paramSet = false;
    boolean worldedit = false;

    for (int i = 0; i < args.size(); i++) {
      String arg = args.get(i);
      if (arg.isEmpty()) continue;

      if (!paramSet) {
        if (arg.length() < 2)
          throw new IllegalArgumentException("Invalid argument format: &7" + arg);
        if (!arg.substring(1, 2).equals(":")) {
          if (arg.contains(":"))
            throw new IllegalArgumentException("Invalid argument format: &7" + arg);

          // No arg specified, treat as player
          players.add(arg);
          continue;
        }

        lastParam = arg.substring(0, 1).toLowerCase();
        paramSet = true;

        if (arg.length() == 2) {
          if (i == (args.size() - 1)) // No values specified
          throw new IllegalArgumentException("Invalid argument format: &7" + arg);
          else // User put a space between the colon and value
          continue;
        }

        // Get values out of argument
        arg = arg.substring(2);
      }

      if (paramSet) {
        if (arg.isEmpty()) {
          throw new IllegalArgumentException("Invalid argument format: &7" + lastParam + ":");
        }

        String[] values = arg.split(",");

        // Players
        if (lastParam.equals("p")) for (String p : values) players.add(p);
        // Worlds
        else if (lastParam.equals("w")) worlds = values;
        // Filters
        else if (lastParam.equals("f")) {
          if (filters != null) filters = Util.concat(filters, values);
          else filters = values;
        }
        // Blocks
        else if (lastParam.equals("b")) {
          for (int j = 0; j < values.length; j++) {
            if (Material.getMaterial(values[j]) != null)
              values[j] = Integer.toString(Material.getMaterial(values[j]).getId());
          }
        }
        // Actions
        else if (lastParam.equals("a")) {
          for (String value : values) {
            DataType type = DataType.fromName(value);
            if (type == null)
              throw new IllegalArgumentException("Invalid action supplied: &7" + value);
            if (!Util.hasPerm(player, "search." + type.getConfigName().toLowerCase()))
              throw new IllegalArgumentException(
                  "You do not have permission to search for: &7" + type.getConfigName());
            actions.add(type);
          }
        }
        // Location
        else if (lastParam.equals("l") && player instanceof Player) {
          if (values[0].equalsIgnoreCase("here")) loc = ((Player) player).getLocation().toVector();
          else {
            loc = new Vector();
            loc.setX(Integer.parseInt(values[0]));
            loc.setY(Integer.parseInt(values[1]));
            loc.setZ(Integer.parseInt(values[2]));
          }
        }
        // Radius
        else if (lastParam.equals("r") && player instanceof Player) {
          if (!Util.isInteger(values[0])) {
            if ((values[0].equalsIgnoreCase("we") || values[0].equalsIgnoreCase("worldedit"))
                && HawkEye.worldEdit != null) {
              Selection sel = HawkEye.worldEdit.getSelection((Player) player);
              double lRadius = Math.ceil(sel.getLength() / 2);
              double wRadius = Math.ceil(sel.getWidth() / 2);
              double hRadius = Math.ceil(sel.getHeight() / 2);

              if (Config.MaxRadius != 0
                  && (lRadius > Config.MaxRadius
                      || wRadius > Config.MaxRadius
                      || hRadius > Config.MaxRadius))
                throw new IllegalArgumentException(
                    "Selection too large, max radius: &7" + Config.MaxRadius);

              worldedit = true;
              minLoc =
                  new Vector(
                      sel.getMinimumPoint().getX(),
                      sel.getMinimumPoint().getY(),
                      sel.getMinimumPoint().getZ());
              maxLoc =
                  new Vector(
                      sel.getMaximumPoint().getX(),
                      sel.getMaximumPoint().getY(),
                      sel.getMaximumPoint().getZ());
            } else {
              throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]);
            }
          } else {
            radius = Integer.parseInt(values[0]);
            if (Config.MaxRadius != 0 && radius > Config.MaxRadius)
              throw new IllegalArgumentException(
                  "Radius too large, max allowed: &7" + Config.MaxRadius);
          }
        }
        // Time
        else if (lastParam.equals("t")) {

          int type = 2;
          boolean isTo = false;
          for (int j = 0; j < arg.length(); j++) {
            String c = arg.substring(j, j + 1);
            if (!Util.isInteger(c)) {
              if (c.equals("m")
                  || c.equals("s")
                  || c.equals("h")
                  || c.equals("d")
                  || c.equals("w")) {
                type = 0;
              }
              if (c.equals("-") || c.equals(":")) type = 1;
            }
          }

          // If the time is in the format '0w0d0h0m0s'
          if (type == 0) {

            int weeks = 0;
            int days = 0;
            int hours = 0;
            int mins = 0;
            int secs = 0;

            String nums = "";
            for (int j = 0; j < values[0].length(); j++) {
              String c = values[0].substring(j, j + 1);
              if (c.equals("!")) { // If the number has a ! infront of it the time inverts
                c = values[0].substring(j, j + 2).replace("!", "");
                isTo = true;
              } else {
                if (Util.isInteger(c)) {
                  nums += c;
                  continue;
                }

                int num = Integer.parseInt(nums);
                if (c.equals("w")) weeks = num;
                else if (c.equals("d")) days = num;
                else if (c.equals("h")) hours = num;
                else if (c.equals("m")) mins = num;
                else if (c.equals("s")) secs = num;
                else throw new IllegalArgumentException("Invalid time measurement: &7" + c);
                nums = "";
              }
            }

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks);
            cal.add(Calendar.DAY_OF_MONTH, -1 * days);
            cal.add(Calendar.HOUR, -1 * hours);
            cal.add(Calendar.MINUTE, -1 * mins);
            cal.add(Calendar.SECOND, -1 * secs);
            SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (isTo) dateTo = form.format(cal.getTime());
            else dateFrom = form.format(cal.getTime());
          }

          // If the time is in the format 'yyyy-MM-dd HH:mm:ss'
          else if (type == 1) {
            if (values.length == 1) {
              SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");
              dateFrom = form.format(Calendar.getInstance().getTime()) + " " + values[0];
            }
            if (values.length >= 2) dateFrom = values[0] + " " + values[1];
            if (values.length == 4) dateTo = values[2] + " " + values[3];
          }
          // Invalid time format
          else if (type == 2) throw new IllegalArgumentException("Invalid time format!");

        } else throw new IllegalArgumentException("Invalid parameter supplied: &7" + lastParam);

        paramSet = false;
      }
    }

    // Sort out locations
    if (!worldedit) parseLocations();
  }
Exemplo n.º 17
0
    protected void applyForce() {
      if (!isActive()) return;

      // Calculate speeds based on previous delta, to try to adjust for server lag
      float timeDeltaSeconds = (System.currentTimeMillis() - lastTick) / 1000.0f;
      Vector force = new Vector(0, gravity * timeDeltaSeconds, 0);

      float elevateMagnitude = (float) elevateRate * timeDeltaSeconds;
      float speedMinMagnitude = (float) minSpeed * timeDeltaSeconds;
      float speedMaxMagnitude = (float) maxSpeed * timeDeltaSeconds;

      Location playerLocation = player.getLocation();

      float pitch = playerLocation.getPitch();
      float yaw = playerLocation.getYaw();

      Vector scaledForce = force.clone();

      // scaled based on distance from target height
      /// this is the main levitate action
      int playerHeight = playerLocation.getBlockY();
      int heightDelta = targetHeight - playerHeight;
      if (heightDelta > 0) {
        int heightBoost = heightDelta > 16 ? 16 : heightDelta;
        scaledForce.multiply(heightBoost);
      } else if (heightDelta < 0) {
        scaledForce.setY(0);
      }

      // Trying out a suggestion, in a hacky way- adjust pitch so that "level" is really looking
      // down a bit
      pitch += 15;

      // Adjust target height based on aim
      Vector aim =
          new Vector(
              (0 - Math.sin(Math.toRadians(yaw))),
              (0 - Math.sin(Math.toRadians(pitch))),
              Math.cos(Math.toRadians(yaw)));
      aim.normalize();

      // only ascend if aiming mostly up, and if near the target
      if (heightDelta < 5 && pitch < -45) {
        hoverHeight += (elevateMagnitude * aim.getY());

        // We'll let the player go up higher than max height.
        if (hoverHeight > 255) hoverHeight = 255;
        if (hoverHeight < defaultHoverHeight) hoverHeight = defaultHoverHeight;
        updateTargetHeight();
      }

      // Periodically poll for ground level changes
      if (checkCounter++ > checkFrequency) {
        checkForGround();
      }

      // Steer- faster at higher altitudes, and scaled based on angle away from center (look up or
      // down to stop)
      float multiplier = speedMinMagnitude;
      if (!player.isSneaking()) {
        int heightFactor =
            hoverHeight > maxSpeedAtElevation ? maxSpeedAtElevation : (int) hoverHeight;
        multiplier *= (float) speedMaxMagnitude * heightFactor / maxSpeedAtElevation;
      }
      float verticalMultipler = 1.0f - (float) Math.abs(aim.getY());
      aim.multiply(multiplier * verticalMultipler);
      aim.setY(0);
      scaledForce.add(aim);

      // Logger.getLogger("Minecraft").info("Applying force: (" + scaledForce.getX() + ", " +
      // scaledForce.getY() + ", "+ scaledForce.getZ() + ")");
      player.setVelocity(scaledForce);

      this.lastTick = System.currentTimeMillis();
    }
Exemplo n.º 18
0
  @Override
  public void rightClick(final Player player) {
    long cooldown;
    if (item.getHasPermission() == true && player.hasPermission(item.getPermission()) == false) {
    } else {
      RPGValue value = RPGValue.get(player, item, "rumble.cooldown");
      if (value == null) {
        cooldown = System.currentTimeMillis() / 50;
        value = new RPGValue(player, item, "rumble.cooldown", cooldown);
      } else {
        cooldown = value.asLong();
      }
      if (cooldown <= System.currentTimeMillis() / 50) {
        value.set(System.currentTimeMillis() / 50 + cooldownTime);
        final Location location = player.getLocation().add(0, -0.2, 0);
        final Vector direction = player.getLocation().getDirection();
        direction.setY(0);
        direction.normalize();
        BukkitRunnable task =
            new BukkitRunnable() {

              private int count = 0;

              public void run() {
                Location above = location.clone().add(0, 1, 0);
                if (above.getBlock().getType().isSolid()
                    || !location.getBlock().getType().isSolid()) {
                  cancel();
                  return;
                }

                Location temp = location.clone();
                for (int x = -2; x <= 2; x++) {
                  for (int z = -2; z <= 2; z++) {
                    temp.setX(x + location.getBlockX());
                    temp.setZ(z + location.getBlockZ());
                    Block block = temp.getBlock();
                    temp.getWorld().playEffect(temp, Effect.STEP_SOUND, block.getTypeId());
                  }
                }
                Entity[] near = getNearbyEntities(location, 1.5);
                boolean hit = false;
                Random random = new Random();
                for (Entity e : near) {
                  if (e != player) {
                    hit = true;
                    break;
                  }
                }
                if (hit) {
                  location
                      .getWorld()
                      .createExplosion(
                          location.getX(), location.getY(), location.getZ(), power, false, false);
                  near = getNearbyEntities(location, 2.5);
                  for (Entity e : near) {
                    if (e != player)
                      e.setVelocity(
                          new Vector(
                              random.nextGaussian() / 4d,
                              1d + random.nextDouble() * (double) power,
                              random.nextGaussian() / 4d));
                  }
                  cancel();
                  return;
                }
                location.add(direction);
                if (count >= distance) {
                  cancel();
                }
                count++;
              }
            };
        task.runTaskTimer(Plugin.plugin, 0, 3);
      } else {
        player.sendMessage(
            ChatColor.AQUA
                + String.format(
                    Locale.get("message.cooldown", Locale.getPlayerLocale(player)),
                    ((double) (cooldown - System.currentTimeMillis() / 50)) / 20d));
      }
    }
  }
Exemplo n.º 19
0
  public void target(TargetMode mode) {
    targetMode = mode == null ? TargetMode.STABILIZE : mode;
    switch (targetMode) {
      case FLEE:
      case HUNT:
      case DIRECTED:
        Target bestTarget = null;
        reverseTargetDistanceScore = true;
        if (targetType == TargetType.ANY || targetType == TargetType.MOB) {
          List<Entity> entities =
              CompatibilityUtils.getNearbyEntities(
                  center, huntMaxRange, huntMaxRange, huntMaxRange);
          for (Entity entity : entities) {
            // We'll get the players from the Mages list
            if (entity instanceof Player || !(entity instanceof LivingEntity) || entity.isDead())
              continue;
            if (!entity.getLocation().getWorld().equals(center.getWorld())) continue;
            LivingEntity li = (LivingEntity) entity;
            if (li.hasPotionEffect(PotionEffectType.INVISIBILITY)) continue;
            Target newScore =
                new Target(center, entity, huntMinRange, huntMaxRange, huntFov, false);
            int score = newScore.getScore();
            if (bestTarget == null || score > bestTarget.getScore()) {
              bestTarget = newScore;
            }
          }
        }
        if (targetType == TargetType.MAGE
            || targetType == TargetType.AUTOMATON
            || targetType == TargetType.ANY
            || targetType == TargetType.PLAYER) {
          Collection<Mage> mages = controller.getMages();
          for (Mage mage : mages) {
            if (mage == this.mage) continue;
            if (targetType == TargetType.AUTOMATON && mage.getPlayer() != null) continue;
            if (targetType == TargetType.PLAYER && mage.getPlayer() == null) continue;
            if (mage.isDead() || !mage.isOnline() || !mage.hasLocation()) continue;
            if (!mage.getLocation().getWorld().equals(center.getWorld())) continue;
            if (!mage.getLocation().getWorld().equals(center.getWorld())) continue;

            if (!mage.isPlayer()) {
              // Check for automata of the same type, kinda hacky.. ?
              Block block = mage.getLocation().getBlock();
              if (block.getType() == Material.COMMAND) {
                BlockState blockState = block.getState();
                if (blockState != null && blockState instanceof CommandBlock) {
                  CommandBlock command = (CommandBlock) blockState;
                  String commandString = command.getCommand();
                  if (commandString != null
                      && commandString.length() > 0
                      && commandString.startsWith("cast " + spell.getKey())) {
                    continue;
                  }
                }
              }
            } else {
              Player player = mage.getPlayer();
              if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) continue;
            }

            Target newScore = new Target(center, mage, huntMinRange, huntMaxRange, huntFov, false);
            int score = newScore.getScore();
            if (bestTarget == null || score > bestTarget.getScore()) {
              bestTarget = newScore;
            }
          }
        }

        if (bestTarget != null) {
          String targetDescription =
              bestTarget.getEntity() == null
                  ? "NONE"
                  : ((bestTarget instanceof Player)
                      ? ((Player) bestTarget.getEntity()).getName()
                      : bestTarget.getEntity().getType().name());

          if (DEBUG) {
            controller
                .getLogger()
                .info(
                    " *Tracking "
                        + targetDescription
                        + " score: "
                        + bestTarget.getScore()
                        + " location: "
                        + center
                        + " -> "
                        + bestTarget.getLocation()
                        + " move "
                        + commandMoveRangeSquared);
          }
          Vector direction = null;

          if (targetMode == TargetMode.DIRECTED) {
            direction = bestTarget.getLocation().getDirection();
            if (DEBUG) {
              controller.getLogger().info(" *Directed: " + direction);
            }
          } else {
            Location targetLocation = bestTarget.getLocation();
            direction = targetLocation.toVector().subtract(center.toVector());
          }

          if (direction != null) {
            center.setDirection(direction);
          }

          // Check for obstruction
          // TODO Think about this more..
          /*
          Block block = spell.getInteractBlock();
          if (block.getType() != Material.AIR && block.getType() != POWER_MATERIAL && !!birthMaterial.is(block)) {
          	// TODO: Use location.setDirection in 1.7+
          	center = CompatibilityUtils.setDirection(center, new Vector(0, 1, 0));
          }
          */

          if (level != null
              && center.distanceSquared(bestTarget.getLocation()) < castRange * castRange) {
            level.onTick(mage, birthMaterial);
          }

          // After ticking, re-position for movement. This way spells still fire towards the target.
          if (targetMode == TargetMode.FLEE) {
            direction = direction.multiply(-1);
            // Don't Flee upward
            if (direction.getY() > 0) {
              direction.setY(-direction.getY());
            }
          }
        }
        break;
      case GLIDE:
        reverseTargetDistanceScore = true;
        break;
      default:
        reverseTargetDistanceScore = false;
    }
  }
Exemplo n.º 20
0
  @EventHandler(priority = EventPriority.HIGHEST)
  private void onInteract(PlayerInteractEvent event) {
    final Player player = event.getPlayer();
    PlayerDataClass playerData = plugin.getPlayerHandler().findPlayer(player.getDisplayName());

    if (playerData.getType() != null) {
      if (player.getItemInHand().getType() == Material.BOW
          && event.getAction() == Action.RIGHT_CLICK_BLOCK
          && (inJump.get(player) == null || inJump.get(player).equals(Boolean.FALSE))
          && playerData.getType().equalsIgnoreCase("soldier")) {

        if (player.getInventory().contains(Material.ARROW)) {
          player.getInventory().removeItem(new ItemStack(Material.ARROW, 1));
          player.updateInventory();
          player
              .getLocation()
              .getWorld()
              .createExplosion(
                  player.getLocation().getX(),
                  player.getLocation().getY(),
                  player.getLocation().getZ(),
                  0);

          // double rotation = player.getLocation().getPitch();

          // double jumpFactor = -(rotation / 20);
          // double distanceFactor = -((90 - rotation) * 10);

          Vector newDirection = player.getVelocity();
          inJump.put(player, true);
          /*if (jumpFactor < -1) {
          	newDirection.setY(newDirection.getY() * jumpFactor);
          }
          if (distanceFactor < -1) {
          	newDirection.setX(newDirection.getX() * distanceFactor);
          	newDirection.setZ(newDirection.getZ() * distanceFactor);
          }

          player.setVelocity(newDirection);*/
          Vector jumpDirection = player.getLocation().getDirection().multiply(-1.5);
          jumpDirection.setX(jumpDirection.getX() * 1.4);
          jumpDirection.setZ(jumpDirection.getZ() * 1.4);
          newDirection.setX(newDirection.getX() * -jumpDirection.getX());
          newDirection.setY(newDirection.getY() * -jumpDirection.getY());
          newDirection.setZ(newDirection.getZ() * -jumpDirection.getZ());
          player.setVelocity(jumpDirection);
          player.damage(3);
          plugin
              .getServer()
              .getScheduler()
              .scheduleSyncDelayedTask(
                  plugin,
                  new Runnable() {
                    public void run() {
                      inJump.put(player, false);
                    }
                  },
                  10L);
          return;
        }
      }
      /* if (player.getItemInHand().getType() == Material.BOW &&
      		event.getAction() == Action.RIGHT_CLICK_AIR &&
      		playerData.getType().equalsIgnoreCase("soldier")) {

           		if (player.getInventory().contains(Material.ARROW)) {
           			player.getInventory().removeItem(new ItemStack (Material.ARROW, 1));
           			player.updateInventory();
           			//Location loc = player.getLocation(); // Get the player Location
           			//loc.add(0, 1, 0); //Add 1 to the Y, makes the arrow go at chest level instead of feet

           			Location arrowLocation = player.getEyeLocation();
        			arrowLocation.setY(arrowLocation.getY() + 0.1);
                 Arrow sniperArrow = player.getWorld().spawnArrow(arrowLocation,
                 player.getLocation().getDirection(), 0.6f, 1);
                 sniperArrow.setShooter(player);
                 sniperArrow.setBounce(false);
                 //sniperArrow.setVelocity(player.getLocation().getDirection().normalize().multiply(12));
        		}

            	return;
      }	*/

      /*if (player.getItemInHand().getType() == Material.BOW &&
      		(event.getAction() == Action.LEFT_CLICK_AIR ||
      		event.getAction() == Action.LEFT_CLICK_BLOCK) &&
      		playerData.getType().equalsIgnoreCase("soldier")) {
      	event.setCancelled(true);
      	return;
      }	*/
      if (player.getItemInHand().getType() == Material.IRON_SWORD
          && (event.getAction() == Action.RIGHT_CLICK_AIR
              || event.getAction() == Action.RIGHT_CLICK_BLOCK)
          && playerData.getType().equalsIgnoreCase("spy")) {

        plugin
            .getServer()
            .getWorld("world")
            .playEffect(player.getLocation(), Effect.EXTINGUISH, 40);

        if (playerData.getDisguised() == null) {
          if (playerData.getTeam() == "red") {
            if (plugin.getPlayerHandler().getBluePlayers().size() > 0) {
              plugin.getPlayerHandler().giveArmor(playerData.getName(), "blue");
              Random random = new Random();
              List<PlayerDataClass> temp = plugin.getPlayerHandler().getBluePlayers();
              int randomNumber = random.nextInt(temp.size());
              playerData.setDisguised(temp.get(randomNumber).getName());
              plugin.getPlayerLocationListener().getRedPlayersOnPoint().remove(playerData);
              TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
            } else {
              plugin.getPlayerHandler().giveArmor(playerData.getName(), "blue");
              playerData.setDisguised(playerData.getName());
              TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
            }
          }
          if (playerData.getTeam() == "blue") {
            if (plugin.getPlayerHandler().getRedPlayers().size() > 0) {
              plugin.getPlayerHandler().giveArmor(playerData.getName(), "red");
              Random random = new Random();
              List<PlayerDataClass> temp = plugin.getPlayerHandler().getRedPlayers();
              int randomNumber = random.nextInt(temp.size());
              playerData.setDisguised(temp.get(randomNumber).getName());
              TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
            } else {
              plugin.getPlayerHandler().giveArmor(playerData.getName(), "red");
              playerData.setDisguised(playerData.getName());
              TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
            }
          }
          return;
        } else {
          playerData.setDisguised(null);
          plugin.getPlayerHandler().giveArmor(playerData.getName(), playerData.getTeam());
          TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
          return;
        }
      }

      if ((event.getAction() == Action.LEFT_CLICK_AIR
              || event.getAction() == Action.LEFT_CLICK_BLOCK
              || event.getAction() == Action.RIGHT_CLICK_AIR
              || event.getAction() == Action.RIGHT_CLICK_BLOCK)
          && playerData.getType().equalsIgnoreCase("spy")
          && playerData.getDisguised() != null) {
        playerData.setDisguised(null);
        plugin.getPlayerHandler().giveArmor(playerData.getName(), playerData.getTeam());
        TagAPI.refreshPlayer(plugin.getServer().getPlayer(playerData.getName()));
        return;
      }

      if (player.getItemInHand().getType() == Material.BOW
          && event.getAction() == Action.LEFT_CLICK_AIR
          && playerData.getType().equalsIgnoreCase("sniper")) {
        if (playerData.isScoped() == true) {
          setUnscoped(player, playerData);
        } else {
          setScoped(player, playerData);
        }
      }

      if (player.getItemInHand().getType() == Material.getMaterial(356)
          && (event.getAction() == Action.LEFT_CLICK_AIR
              || event.getAction() == Action.LEFT_CLICK_BLOCK)
          && playerData.getType().equalsIgnoreCase("demo")) {
        plugin.getLogger().info("demo fired");

        Location stickyLocation = player.getEyeLocation();
        stickyLocation.setY(stickyLocation.getY() + 0.1);

        Item sticky;
        if (playerData.getTeam().equals("red")) {
          sticky =
              player
                  .getWorld()
                  .dropItemNaturally(
                      stickyLocation,
                      new ItemStack(
                          Material.INK_SACK, 1, (short) 0, (byte) (15 - DyeColor.RED.getData())));
          sticky.setMetadata("redsticky", new FixedMetadataValue(plugin, true));
        } else {
          sticky =
              player
                  .getWorld()
                  .dropItemNaturally(
                      stickyLocation,
                      new ItemStack(
                          Material.INK_SACK, 1, (short) 0, (byte) (15 - DyeColor.BLUE.getData())));
          sticky.setMetadata("bluesticky", new FixedMetadataValue(plugin, true));
        }

        // stickyBomb.setData(dye);
        // Item sticky = player.getWorld().dropItem(stickyLocation, stickyBomb);

        sticky.setVelocity(player.getEyeLocation().getDirection());

        StickyDataClass stickyData = new StickyDataClass();
        stickyData.setOwner(playerData.getName());
        stickyData.setSticky(sticky);
        stickyData.setTeam(playerData.getTeam());
        plugin.getStickysFired().add(stickyData);
      }

      if (player.getItemInHand().getType() == Material.getMaterial(356)
          && (event.getAction() == Action.RIGHT_CLICK_AIR
              || event.getAction() == Action.RIGHT_CLICK_BLOCK)
          && playerData.getType().equalsIgnoreCase("demo")) {
        plugin.getLogger().info("demo triggered");
        event.setCancelled(true);
        for (int i = 0; i < plugin.getStickysFired().size(); i++) {
          StickyDataClass temp = plugin.getStickysFired().get(i);
          plugin.getLogger().info(i + " Owner/Team " + temp.getOwner() + "/" + temp.getTeam());
          if (temp.getOwner() == playerData.getName()) {
            plugin
                .getServer()
                .getWorld("world")
                .createExplosion(
                    temp.getSticky().getLocation().getX(),
                    temp.getSticky().getLocation().getY(),
                    temp.getSticky().getLocation().getZ(),
                    5,
                    false,
                    false);

            for (Entity nearby : temp.getSticky().getNearbyEntities(3, 3, 3)) {
              if (nearby instanceof Player) {
                Player nearbyPlayer = (Player) nearby;
                nearbyPlayer.damage(8, player);
              }
            }
            temp.getSticky().remove();
            plugin.getStickysFired().remove(i);
          }
        }
      }

    } else {
      return;
    }
  }
Exemplo n.º 21
0
  @Override
  public SpellResult perform(CastContext context) {
    Block targetBlock = context.getTargetBlock();
    Entity currentEntity = current == null ? null : current.get();
    current = null;
    if (currentEntity != null) {
      currentEntity.remove();
    }

    targetBlock = targetBlock.getRelative(BlockFace.UP);

    Location spawnLocation = targetBlock.getLocation();
    Location sourceLocation = context.getLocation();
    spawnLocation.setPitch(sourceLocation.getPitch());
    spawnLocation.setYaw(sourceLocation.getYaw());

    MageController controller = context.getController();
    if (entityData == null) {
      String randomType = RandomUtils.weightedRandom(entityTypeProbability);
      try {
        entityData = controller.getMob(randomType);
        if (entityData == null) {
          entityData =
              new com.elmakers.mine.bukkit.entity.EntityData(
                  EntityType.valueOf(randomType.toUpperCase()));
        }
      } catch (Throwable ex) {
        entityData = null;
      }
    }
    if (entityData == null) {
      return SpellResult.FAIL;
    }

    if (force) {
      controller.setForceSpawn(true);
    }
    Entity spawnedEntity = null;
    try {
      spawnedEntity = entityData.spawn(context.getController(), spawnLocation, spawnReason);
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    if (force) {
      controller.setForceSpawn(false);
    }

    if (spawnedEntity == null) {
      return SpellResult.FAIL;
    }

    if (!loot) {
      spawnedEntity.setMetadata("nodrops", new FixedMetadataValue(controller.getPlugin(), true));
    }
    if (speed > 0) {
      Vector motion = direction;
      if (motion == null) {
        motion = context.getDirection();
      } else {
        motion = motion.clone();
      }

      if (dyOffset != 0) {
        motion.setY(motion.getY() + dyOffset);
      }
      motion.normalize();
      motion.multiply(speed);
      CompatibilityUtils.setEntityMotion(spawnedEntity, motion);
    }

    Collection<EffectPlayer> projectileEffects = context.getEffects("spawned");
    for (EffectPlayer effectPlayer : projectileEffects) {
      effectPlayer.start(spawnedEntity.getLocation(), spawnedEntity, null, null);
    }
    context.registerForUndo(spawnedEntity);

    if (track) {
      current = new WeakReference<Entity>(spawnedEntity);
    }
    if (setTarget) {
      context.setTargetEntity(spawnedEntity);
    }
    return SpellResult.CAST;
  }
Exemplo n.º 22
0
  @Override
  protected void onPlayerMove(PlayerMoveEvent evt, Player P) {
    // TODO Auto-generated method stub
    super.onPlayerMove(evt, P);
    Player ply = evt.getPlayer();
    if (isSpectator(ply)) return;
    if (JocIniciat) {
      Player plyr = evt.getPlayer();

      Location to = evt.getTo();
      Location from = evt.getFrom();

      int equip = obtenirEquip(ply).getId() + 1;
      if (ply.getLocation().getY() < 102) {
        ply.setFireTicks(5000);
      }
      if (ply.getLocation().getY() < 60) {
        ply.damage(10000);
      }

      // Torres escuts
      int e = 1;
      while (e <= 2) {
        int i = 0;
        while (i <= 1) {
          Cuboid cub =
              pMapaActual()
                  .ObtenirCuboid("RegT" + Integer.toString(e) + Integer.toString(i), getWorld());
          Location center = cub.getCenter();
          if (cub.contains(to.getBlock())) {
            if (e == equip) {
              Vector vec = Utils.CrearVector(center, from).normalize().add(new Vector(0, 1, 0));
              getWorld().playSound(to, Sound.IRONGOLEM_HIT, 1F, 2.2F);
              getWorld().playEffect(to, Effect.MOBSPAWNER_FLAMES, 3);
              getWorld()
                  .playEffect(to.clone().add(new Vector(0, 1, 0)), Effect.MOBSPAWNER_FLAMES, 3);
              if (cub.contains(from.getBlock()) && plyr.getVelocity().length() >= 1) {
                plyr.teleport(from.add(vec));
                // Bukkit.broadcastMessage("ha entrat");
              } else {
                plyr.setVelocity(vec);
              }
              // evt.setCancelled(true);

            }
          }
          i = i + 1;
        }
        e = e + 1;
      }
      // SECURE NO-FALL
      //
      boolean isNoFallActive = false;

      ItemStack itemInHand = ply.getItemInHand();
      if (itemInHand.hasItemMeta()) {
        ItemMeta itemMeta = itemInHand.getItemMeta();
        if (itemMeta.hasDisplayName()) {
          if (itemMeta.getDisplayName().equals(getBridgeToolName())) {
            isNoFallActive = true;
          }
        }
      }

      if (isNoFallActive) {
        Vector v = Utils.CrearVector(evt.getFrom(), evt.getTo());
        v.multiply(1.45D);
        v.setY(0);
        Block bDown = evt.getTo().add(v).getBlock().getRelative(BlockFace.DOWN);
        if (bDown.isEmpty() && bDown.getRelative(BlockFace.DOWN).isEmpty()) {
          ItemStack placeableItemStack = getPlaceableItemStack(ply);
          if (placeableItemStack != null) {
            bDown.setType(placeableItemStack.getType());
            bDown.setData(placeableItemStack.getData().getData());
            ItemStack sampleIt = new ItemStack(placeableItemStack);
            sampleIt.setAmount(1);
            ply.getInventory().removeItem(sampleIt);
            itemInHand.setDurability((short) (itemInHand.getDurability() + 3));
          }
        }
      }
    }
  }
Exemplo n.º 23
0
  @Override
  public void progress() {
    progressCounter++;
    if (player.isDead() || !player.isOnline()) {
      remove();
      return;
    } else if (currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) {
      remove();
      return;
    }

    if (abilityName.equalsIgnoreCase("Twister")) {
      if (destination == null) {
        state = AbilityState.TWISTER_MOVING;
        direction = player.getEyeLocation().getDirection().clone().normalize();
        direction.setY(0);
        origin = player.getLocation().add(direction.clone().multiply(2));
        destination = player.getLocation().add(direction.clone().multiply(range));
        currentLoc = origin.clone();
      }
      if (origin.distanceSquared(currentLoc) < origin.distanceSquared(destination)
          && state == AbilityState.TWISTER_MOVING) {
        currentLoc.add(direction.clone().multiply(speed));
      } else if (state == AbilityState.TWISTER_MOVING) {
        state = AbilityState.TWISTER_STATIONARY;
        time = System.currentTimeMillis();
      } else if (System.currentTimeMillis() - time >= twisterRemoveDelay) {
        remove();
        return;
      } else if (GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) {
        remove();
        return;
      }

      Block topBlock = GeneralMethods.getTopBlock(currentLoc, 3, -3);
      if (topBlock == null) {
        remove();
        return;
      }
      currentLoc.setY(topBlock.getLocation().getY());

      double height = twisterHeight;
      double radius = twisterRadius;
      for (double y = 0; y < height; y += twisterHeightParticles) {
        double animRadius = ((radius / height) * y);
        for (double i = -180; i <= 180; i += twisterDegreeParticles) {
          Vector animDir = GeneralMethods.rotateXZ(new Vector(1, 0, 1), i);
          Location animLoc = currentLoc.clone().add(animDir.multiply(animRadius));
          animLoc.add(0, y, 0);
          playAirbendingParticles(animLoc, 1, 0, 0, 0);
        }
      }
      playAirbendingSound(currentLoc);

      for (int i = 0; i < height; i += 3) {
        for (Entity entity :
            GeneralMethods.getEntitiesAroundPoint(currentLoc.clone().add(0, i, 0), radius * 0.75)) {
          if (!affectedEntities.contains(entity) && !entity.equals(player)) {
            affectedEntities.add(entity);
          }
        }
      }

      for (Entity entity : affectedEntities) {
        Vector forceDir =
            GeneralMethods.getDirection(entity.getLocation(), currentLoc.clone().add(0, height, 0));
        if (entity instanceof Player) {
          if (Commands.invincible.contains(((Player) entity).getName())) {
            break;
          }
        }
        entity.setVelocity(forceDir.clone().normalize().multiply(0.3));
      }
    } else if (abilityName.equalsIgnoreCase("AirStream")) {
      if (destination == null) {
        origin = player.getEyeLocation();
        currentLoc = origin.clone();
      }
      Entity target = GeneralMethods.getTargetedEntity(player, range);
      if (target instanceof Player) {
        if (Commands.invincible.contains(((Player) target).getName())) {
          return;
        }
      }

      if (target != null && target.getLocation().distanceSquared(currentLoc) > 49) {
        destination = target.getLocation();
      } else {
        destination = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterial());
      }

      direction = GeneralMethods.getDirection(currentLoc, destination).normalize();
      currentLoc.add(direction.clone().multiply(speed));

      if (player.getWorld() != currentLoc.getWorld()) {
        remove();
        return;
      } else if (!player.isSneaking()) {
        remove();
        return;
      } else if (player.getWorld().equals(currentLoc.getWorld())
          && Math.abs(player.getLocation().distanceSquared(currentLoc)) > range * range) {
        remove();
        return;
      } else if (affectedEntities.size() > 0
          && System.currentTimeMillis() - time >= airStreamEntityCarryDuration) {
        remove();
        return;
      } else if (!isTransparent(currentLoc.getBlock())) {
        remove();
        return;
      } else if (currentLoc.getY() - origin.getY() > airStreamMaxEntityHeight) {
        remove();
        return;
      } else if (GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) {
        remove();
        return;
      } else if (FireAbility.isWithinFireShield(currentLoc)) {
        remove();
        return;
      } else if (isWithinAirShield(currentLoc)) {
        remove();
        return;
      } else if (!isTransparent(currentLoc.getBlock())) {
        currentLoc.subtract(direction.clone().multiply(speed));
      }

      for (int i = 0; i < 10; i++) {
        BukkitRunnable br =
            new BukkitRunnable() {
              final Location loc = currentLoc.clone();
              final Vector dir = direction.clone();

              @Override
              public void run() {
                for (int angle = -180; angle <= 180; angle += 45) {
                  Vector orthog = GeneralMethods.getOrthogonalVector(dir.clone(), angle, 0.5);
                  playAirbendingParticles(loc.clone().add(orthog), 1, 0F, 0F, 0F);
                }
              }
            };
        br.runTaskLater(ProjectKorra.plugin, i * 2);
        tasks.add(br);
      }

      for (Entity entity : GeneralMethods.getEntitiesAroundPoint(currentLoc, 2.8)) {
        if (affectedEntities.size() == 0) {
          // Set the timer to remove the ability
          time = System.currentTimeMillis();
        }
        if (!entity.equals(player) && !affectedEntities.contains(entity)) {
          affectedEntities.add(entity);
          if (entity instanceof Player) {
            flights.add(new Flight((Player) entity, player));
          }
        }
      }

      for (Entity entity : affectedEntities) {
        Vector force = GeneralMethods.getDirection(entity.getLocation(), currentLoc);
        entity.setVelocity(force.clone().normalize().multiply(speed));
        entity.setFallDistance(0F);
      }
    } else if (abilityName.equalsIgnoreCase("AirSweep")) {
      if (origin == null) {
        direction = player.getEyeLocation().getDirection().normalize();
        origin = player.getLocation().add(direction.clone().multiply(10));
      }
      if (progressCounter < 8) {
        return;
      }
      if (destination == null) {
        destination =
            player
                .getLocation()
                .add(player.getEyeLocation().getDirection().normalize().multiply(10));
        Vector origToDest = GeneralMethods.getDirection(origin, destination);
        for (double i = 0; i < 30; i++) {
          Vector vec =
              GeneralMethods.getDirection(
                  player.getLocation(), origin.clone().add(origToDest.clone().multiply(i / 30)));

          FireComboStream fs =
              new FireComboStream(null, vec, player.getLocation(), range, speed, "AirSweep");
          fs.setDensity(1);
          fs.setSpread(0F);
          fs.setUseNewParticles(true);
          fs.setParticleEffect(getAirbendingParticles());
          fs.setCollides(false);
          fs.runTaskTimer(ProjectKorra.plugin, (long) (i / 2.5), 1L);
          tasks.add(fs);
        }
      }
      manageAirVectors();
    }
  }