Java Code Examples for org.bukkit.util.Vector

The following examples show how to use org.bukkit.util.Vector. These examples are extracted from open source projects. 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 Project: NovaGuilds   Author: MarcinWieczorek   File: ParticleUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets circle vectors
 *
 * @param radius    radius of a circle
 * @param precision precision (amount of vectors)
 * @return list of vectors
 */
public static List<Vector> getCircleVectors(int radius, int precision) {
	final List<Vector> list = new ArrayList<>();

	for(int i = 0; i < precision; i++) {
		double p1 = (i * Math.PI) / (precision / 2);
		double p2 = (((i == 0) ? precision : i - 1) * Math.PI) / (precision / 2);

		double x1 = Math.cos(p1) * radius;
		double x2 = Math.cos(p2) * radius;
		double z1 = Math.sin(p1) * radius;
		double z2 = Math.sin(p2) * radius;

		Vector vec = new Vector(x2 - x1, 0, z2 - z1);
		list.add(vec);
	}

	return list;
}
 
Example #2
Source Project: ProjectAres   Author: OvercastNetwork   File: CoreMatchModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void leakCheck(final BlockTransformEvent event) {
    if(event.getWorld() != this.match.getWorld()) return;

    if(event.getNewState().getType() == Material.STATIONARY_LAVA) {
        Vector blockVector = BlockUtils.center(event.getNewState()).toVector();
        for(Core core : this.cores) {
            if(!core.hasLeaked() && core.getLeakRegion().contains(blockVector)) {
                // core has leaked
                core.markLeaked();
                this.match.getPluginManager().callEvent(new CoreLeakEvent(this.match, core, event.getNewState()));
                this.match.getPluginManager().callEvent(new GoalCompleteEvent(core,
                                                                              true,
                                                                              c -> false,
                                                                              c -> !c.equals(core.getOwner()),
                                                                              core.getContributions()));
            }
        }
    }
}
 
Example #3
Source Project: EffectLib   Author: Slikey   File: BigBangEffect.java    License: MIT License 6 votes vote down vote up
@Override
public void onRun() {
    if (firework == null) {
        Builder b = FireworkEffect.builder().with(fireworkType);
        b.withColor(color).withColor(color2).withColor(color3);
        b.withFade(fadeColor);
        b.trail(true);
        firework = b.build();
    }
    Location location = getLocation();
    for (int i = 0; i < explosions; i++) {
        Vector v = RandomUtils.getRandomVector().multiply(radius);
        detonate(location, v);
        if (soundInterval != 0 && step % soundInterval == 0) {
            location.getWorld().playSound(location, sound, soundVolume, soundPitch);
        }
    }
    step++;
}
 
Example #4
Source Project: PGM   Author: PGMDev   File: GeneralizingListener.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Modify the to location of the given event to prevent the movement and move the player so they
 * are standing on the center of the block at the from location.
 */
private static void resetPosition(final PlayerMoveEvent event) {
  Location newLoc;
  double yValue = event.getFrom().getY();

  if (yValue <= 0 || event instanceof PlayerTeleportEvent) {
    newLoc = event.getFrom();
  } else {
    newLoc = BlockVectors.center(event.getFrom()).subtract(new Vector(0, 0.5, 0));
    if (newLoc.getBlock() != null) {
      switch (newLoc.getBlock().getType()) {
        case STEP:
        case WOOD_STEP:
          newLoc.add(new Vector(0, 0.5, 0));
          break;
        default:
          break;
      }
    }
  }

  newLoc.setPitch(event.getTo().getPitch());
  newLoc.setYaw(event.getTo().getYaw());
  event.setCancelled(false);
  event.setTo(newLoc);
}
 
Example #5
Source Project: EffectLib   Author: Slikey   File: ConeEffect.java    License: 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 #6
Source Project: Hawk   Author: HawkAnticheat   File: MoveEvent.java    License: GNU General Public License v3.0 6 votes vote down vote up
private float computeFriction() {
    float friction = 0.91F;

    //patch some inconsistencies
    boolean teleportBug = pp.getCurrentTick() == pp.getLastTeleportAcceptTick();
    boolean onGround = teleportBug ? pp.isOnGroundReally() : pp.isOnGround();

    if (onGround) {
        Vector pos = pp.getPosition();
        Block b = ServerUtils.getBlockAsync(new Location(pp.getWorld(), pos.getX(), pos.getY() - 1, pos.getZ()));
        if(b != null) {
            friction *= WrappedBlock.getWrappedBlock(b, pp.getClientVersion()).getSlipperiness();
        }
    }
    return friction;
}
 
Example #7
Source Project: CardinalPGM   Author: twizmwazin   File: DoubleJumpKit.java    License: MIT License 6 votes vote down vote up
@EventHandler
public void onPlayerToggleFly(PlayerToggleFlightEvent event) {
    if (!enabled) return;
    Player player = event.getPlayer();
    if (!players.contains(player.getUniqueId()) || player.getExp() > 1.0f || !event.isFlying()) return;
    player.setAllowFlight(false);
    player.setExp(0.0f);
    event.setCancelled(true);

    Vector normal = player.getEyeLocation().getDirection();
    normal.setY(0.75 + Math.max(normal.getY() * 0.5, 0));
    normal.multiply(power / 2);
    event.getPlayer().setVelocity(normal);

    player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ZOMBIE_INFECT, 0.5f, 1.8f);

    update();
}
 
Example #8
Source Project: ProjectAres   Author: OvercastNetwork   File: ControlPointBlockDisplay.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
protected void setProgress(Competitor controllingTeam, Competitor capturingTeam, double capturingProgress) {
    if(this.progressDisplayRegion != null) {
        Vector center = this.progressDisplayRegion.getBounds().center();

        // capturingProgress can be zero, but it can never be one, so invert it to avoid
        // a zero-area SectorRegion that can cause glitchy rendering
        SectorRegion sectorRegion = new SectorRegion(center.getX(), center.getZ(), 0, (1 - capturingProgress) * 2 * Math.PI);

        for(BlockVector pos : this.progressDisplayRegion.getBlockVectors()) {
            if(sectorRegion.contains(pos)) {
                this.setBlock(pos, controllingTeam);
            } else {
                this.setBlock(pos, capturingTeam);
            }
        }
    }
}
 
Example #9
Source Project: TabooLib   Author: TabooLib   File: Vectors.java    License: MIT License 6 votes vote down vote up
public static Item itemDrop(Player player, ItemStack itemStack, double bulletSpread, double radius) {
    Location location = player.getLocation().add(0.0D, 1.5D, 0.0D);
    Item item = player.getWorld().dropItem(location, itemStack);
    double yaw = Math.toRadians((double)(-player.getLocation().getYaw() - 90.0F));
    double pitch = Math.toRadians((double)(-player.getLocation().getPitch()));
    double x;
    double y;
    double z;
    if (bulletSpread > 0.0D) {
        double[] spread = new double[]{1.0D, 1.0D, 1.0D};
        IntStream.range(0, 3).forEach((t) -> {
            spread[t] = (Numbers.getRandom().nextDouble() - Numbers.getRandom().nextDouble()) * bulletSpread * 0.1D;
        });
        x = Math.cos(pitch) * Math.cos(yaw) + spread[0];
        y = Math.sin(pitch) + spread[1];
        z = -Math.sin(yaw) * Math.cos(pitch) + spread[2];
    } else {
        x = Math.cos(pitch) * Math.cos(yaw);
        y = Math.sin(pitch);
        z = -Math.sin(yaw) * Math.cos(pitch);
    }

    Vector dirVel = new Vector(x, y, z);
    item.setVelocity(dirVel.normalize().multiply(radius));
    return item;
}
 
Example #10
Source Project: PGM   Author: PGMDev   File: CoreMatchModule.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void leakCheck(final BlockTransformEvent event) {
  if (event.getWorld() != this.match.getWorld()) return;

  if (event.getNewState().getType() == Material.STATIONARY_LAVA) {
    Vector blockVector = BlockVectors.center(event.getNewState()).toVector();
    for (Core core : this.cores) {
      if (!core.hasLeaked() && core.getLeakRegion().contains(blockVector)) {
        // core has leaked
        core.markLeaked();
        this.match.callEvent(new CoreLeakEvent(this.match, core, event.getNewState()));
        this.match.callEvent(
            new GoalCompleteEvent(
                this.match, core, core.getOwner(), false, core.getContributions()));
      }
    }
  }
}
 
Example #11
Source Project: Hawk   Author: HawkAnticheat   File: MoveEvent.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean testStep() {
    Vector extraVelocity = pp.getVelocity().clone();
    if(pp.isOnGroundReally())
        extraVelocity.setY(-0.0784);
    else
        extraVelocity.setY((extraVelocity.getY() - 0.08) * 0.98);
    Location extraPos = pp.getPosition().toLocation(pp.getWorld());
    extraPos.add(extraVelocity);
    float deltaY = (float) (getTo().getY() - getFrom().getY());
    return AdjacentBlocks.onGroundReally(extraPos, extraVelocity.getY(), false, 0.001, pp) && onGroundReally && deltaY > 0.002F && deltaY <= 0.6F;
}
 
Example #12
Source Project: Skript   Author: SkriptLang   File: EffVectorRotateAroundAnother.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("null")
@Override
protected void execute(Event e) {
	Vector v2 = second.getSingle(e);
	Number d = degree.getSingle(e);
	if (v2 == null || d == null)
		return;
	for (Vector v1 : first.getArray(e))
		VectorMath.rot(v1, v2, d.doubleValue());
}
 
Example #13
Source Project: ProjectAres   Author: OvercastNetwork   File: Rocket.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public Vector getCenter() {
    int num = this.fireworks.size();
    double totalX = 0;
    double totalY = 0;
    double totalZ = 0;

    for(Firework firework : this.fireworks) {
        totalX += firework.getLocation().getX();
        totalY += firework.getLocation().getY();
        totalZ += firework.getLocation().getZ();
    }

    return new Vector(totalX / num, totalY / num, totalZ / num);
}
 
Example #14
Source Project: FastAsyncWorldedit   Author: boy0001   File: ChunkListener.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Prevent FireWorks from loading chunks
 * @param event
 */
@EventHandler(priority = EventPriority.LOWEST)
public void onChunkLoad(ChunkLoadEvent event) {
    if (!Settings.IMP.TICK_LIMITER.FIREWORKS_LOAD_CHUNKS) {
        Chunk chunk = event.getChunk();
        Entity[] entities = chunk.getEntities();
        World world = chunk.getWorld();

        Exception e = new Exception();
        int start = 14;
        int end = 22;
        int depth = Math.min(end, getDepth(e));

        for (int frame = start; frame < depth; frame++) {
            StackTraceElement elem = getElement(e, frame);
            if (elem == null) return;
            String className = elem.getClassName();
            int len = className.length();
            if (className != null) {
                if (len > 15 && className.charAt(len - 15) == 'E' && className.endsWith("EntityFireworks")) {
                    for (Entity ent : world.getEntities()) {
                        if (ent.getType() == EntityType.FIREWORK) {
                            Vector velocity = ent.getVelocity();
                            double vertical = Math.abs(velocity.getY());
                            if (Math.abs(velocity.getX()) > vertical || Math.abs(velocity.getZ()) > vertical) {
                                Fawe.debug("[FAWE `tick-limiter`] Detected and cancelled rogue FireWork at " + ent.getLocation());
                                ent.remove();
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #15
Source Project: Chimera   Author: Pante   File: Vectors.java    License: MIT License 5 votes vote down vote up
public static Vector rotateAroundYAxis(Vector vector, double angle) {
    double cos = cos(angle);
    double sin = sin(angle);
    double x = vector.getX() * cos + vector.getZ() * sin;
    double z = vector.getX() * -sin + vector.getZ() * cos;
    
    return vector.setX(x).setZ(z);
}
 
Example #16
Source Project: EffectLib   Author: Slikey   File: SphereEffect.java    License: MIT License 5 votes vote down vote up
@Override
public void onRun() {
    if (radiusIncrease != 0) {
        radius += radiusIncrease;
    }

    Location location = getLocation();
    location.add(0, yOffset, 0);
    for (int i = 0; i < particles; i++) {
        Vector vector = RandomUtils.getRandomVector().multiply(radius);
        location.add(vector);
        display(particle, location);
        location.subtract(vector);
    }
}
 
Example #17
Source Project: EliteMobs   Author: MagmaGuy   File: Kraken.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void fireballInitializer(Squid kraken, Player target) {

        Location offsetLocation = ProjectileLocationGenerator.generateLocation(kraken, target);
        Fireball repeatingFireball = (Fireball) kraken.getWorld().spawnEntity(offsetLocation, EntityType.FIREBALL);
        Vector targetterToTargetted = target.getEyeLocation().subtract(repeatingFireball.getLocation()).toVector()
                .normalize().multiply(1);

        repeatingFireball.setDirection(targetterToTargetted);
        repeatingFireball.setIsIncendiary(true);
        repeatingFireball.setYield(2F);

        fireballs.add(repeatingFireball);

    }
 
Example #18
Source Project: CardinalPGM   Author: twizmwazin   File: ComplementRegion.java    License: MIT License 5 votes vote down vote up
@Override
public boolean contains(Vector vector) {
    if (!regions.get(0).contains(vector)) return false;
    for (int i = 1; i < regions.size(); i++) {
        if (regions.get(i).contains(vector)) return false;
    }
    return true;
}
 
Example #19
Source Project: Skript   Author: SkriptLang   File: WorldGuard6Hook.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
        public Iterator<Block> getBlocks() {
            final BlockVector min = region.getMinimumPoint(), max = region.getMaximumPoint();
            return new AABB(world, new Vector(min.getBlockX(), min.getBlockY(), min.getBlockZ()), new Vector(max.getBlockX() + 1, max.getBlockY() + 1, max.getBlockZ() + 1)).iterator();
//          final Iterator<BlockVector2D> iter = region.getPoints().iterator();
//          if (!iter.hasNext())
//              return EmptyIterator.get();
//          return new Iterator<Block>() {
//              @SuppressWarnings("null")
//              BlockVector2D current = iter.next();
//              int height = 0;
//              final int maxHeight = world.getMaxHeight();
//
//              @SuppressWarnings("null")
//              @Override
//              public boolean hasNext() {
//                  if (height >= maxHeight && iter.hasNext()) {
//                      height = 0;
//                      current = iter.next();
//                  }
//                  return height < maxHeight;
//              }
//
//              @SuppressWarnings("null")
//              @Override
//              public Block next() {
//                  if (!hasNext())
//                      throw new NoSuchElementException();
//                  return world.getBlockAt(current.getBlockX(), height++, current.getBlockZ());
//              }
//
//              @Override
//              public void remove() {
//                  throw new UnsupportedOperationException();
//              }
//          };
        }
 
Example #20
Source Project: EffectLib   Author: Slikey   File: RandomUtils.java    License: MIT License 5 votes vote down vote up
public static Vector getRandomVector() {
    double x, y, z;
    x = random.nextDouble() * 2 - 1;
    y = random.nextDouble() * 2 - 1;
    z = random.nextDouble() * 2 - 1;

    return new Vector(x, y, z).normalize();
}
 
Example #21
Source Project: EntityAPI   Author: EntityAPIDev   File: ControllableChickenEntity.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void g(double x, double y, double z) {
    if (this.controllableEntity != null) {
        Vector velocity = this.controllableEntity.getMind().getAttribute(PushAttribute.class).call(this.controllableEntity, new Vector(x, y, z)).getPushVelocity();
        x = velocity.getX();
        y = velocity.getY();
        z = velocity.getZ();
    }
    super.g(x, y, z);
}
 
Example #22
Source Project: EntityAPI   Author: EntityAPIDev   File: ControllableGhastEntity.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void g(double x, double y, double z) {
    if (this.controllableEntity != null) {
        Vector velocity = this.controllableEntity.getMind().getAttribute(PushAttribute.class).call(this.controllableEntity, new Vector(x, y, z)).getPushVelocity();
        x = velocity.getX();
        y = velocity.getY();
        z = velocity.getZ();
    }
    super.g(x, y, z);
}
 
Example #23
Source Project: EntityAPI   Author: EntityAPIDev   File: ControllableWitchEntity.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void g(double x, double y, double z) {
    if (this.controllableEntity != null) {
        Vector velocity = this.controllableEntity.getMind().getAttribute(PushAttribute.class).call(this.controllableEntity, new Vector(x, y, z)).getPushVelocity();
        x = velocity.getX();
        y = velocity.getY();
        z = velocity.getZ();
    }
    super.g(x, y, z);
}
 
Example #24
Source Project: PGM   Author: PGMDev   File: TransformedRegion.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generic bounding box transform - transform all 8 vertices and find the minimum bounding box
 * containing them.
 */
protected Bounds getTransformedBounds() {
  Vector[] oldVertices = this.region.getBounds().getVertices();
  Vector[] newVertices = new Vector[8];
  for (int i = 0; i < oldVertices.length; i++) {
    newVertices[i] = this.transform(oldVertices[i]);
  }
  return new Bounds(newVertices);
}
 
Example #25
Source Project: ProjectAres   Author: OvercastNetwork   File: EventRuleContext.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public EventRule getNearest(Vector pos) {
    EventRule nearest = null;
    double distance = Double.POSITIVE_INFINITY;

    for(EventRule rule : byPriority) {
        double d = pos.distanceSquared(rule.region().getBounds().center());
        if(d < distance) {
            nearest = rule;
            distance = d;
        }
    }

    return nearest;
}
 
Example #26
Source Project: PGM   Author: PGMDev   File: Net.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public Net(
    @Nullable String id,
    Region region,
    Filter captureFilter,
    Filter respawnFilter,
    @Nullable FeatureReference<TeamFactory> owner,
    double pointsPerCapture,
    boolean sticky,
    @Nullable Component denyMessage,
    @Nullable Component respawnMessage,
    @Nullable Post returnPost,
    ImmutableSet<FlagDefinition> capturableFlags,
    ImmutableSet<FlagDefinition> recoverableFlags,
    boolean respawnTogether,
    @Nullable Vector proximityLocation) {

  super(id);
  this.region = region;
  this.captureFilter = captureFilter;
  this.respawnFilter = respawnFilter;
  this.owner = owner;
  this.pointsPerCapture = pointsPerCapture;
  this.sticky = sticky;
  this.denyMessage = denyMessage;
  this.respawnMessage = respawnMessage;
  this.returnPost = returnPost;
  this.capturableFlags = capturableFlags;
  this.recoverableFlags = recoverableFlags;
  this.respawnTogether = respawnTogether;
  this.proximityLocation = proximityLocation;
}
 
Example #27
Source Project: EntityAPI   Author: EntityAPIDev   File: ControllableHorseEntity.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void g(double x, double y, double z) {
    if (this.controllableEntity != null) {
        Vector velocity = this.controllableEntity.getMind().getAttribute(PushAttribute.class).call(this.controllableEntity, new Vector(x, y, z)).getPushVelocity();
        x = velocity.getX();
        y = velocity.getY();
        z = velocity.getZ();
    }
    super.g(x, y, z);
}
 
Example #28
Source Project: Hawk   Author: HawkAnticheat   File: EntityInteractDirectionB.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void processMove(MoveEvent e) {
    Player p = e.getPlayer();
    UUID uuid = p.getUniqueId();

    if(lastHitVecMap.containsKey(uuid)) {
        Vector headPos = e.getHawkPlayer().getHeadPosition();
        Vector dirA = MathPlus.getDirection(e.getFrom().getYaw(), e.getTo().getPitch());
        Vector dirB = lastHitVecMap.get(uuid).subtract(headPos).normalize();
        //dirA.dot(dirB) should be close to 1.0
    }

    lastHitVecMap.remove(uuid);
}
 
Example #29
Source Project: PGM   Author: PGMDev   File: RegionParser.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("mirror")
public MirroredRegion parseMirror(Element el) throws InvalidXMLException {
  Vector normal = XMLUtils.parseVector(XMLUtils.getRequiredAttribute(el, "normal"));
  if (normal.lengthSquared() == 0) {
    throw new InvalidXMLException("normal must have a non-zero length", el);
  }

  Vector origin = XMLUtils.parseVector(el.getAttribute("origin"), new Vector());

  return new MirroredRegion(this.parseChildren(el), origin, normal);
}
 
Example #30
Source Project: Slimefun4   Author: TheBusyBiscuit   File: SeismicAxe.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void pushEntity(Player p, Entity entity) {
    Vector vector = entity.getLocation().toVector().subtract(p.getLocation().toVector()).normalize();
    vector.multiply(STRENGTH);
    vector.setY(0.9);
    entity.setVelocity(vector);

    if (entity.getType() != EntityType.PLAYER || p.getWorld().getPVP()) {
        EntityDamageByEntityEvent event = new EntityDamageByEntityEvent(p, entity, DamageCause.ENTITY_ATTACK, 6D);
        Bukkit.getPluginManager().callEvent(event);

        if (!event.isCancelled()) {
            ((LivingEntity) entity).damage(DAMAGE);
        }
    }
}