Solved Spawning items in random 5x5 area

Discussion in 'Plugin Development' started by flash110, Oct 8, 2016.

Thread Status:
Not open for further replies.
  1. Offline

    flash110

    This is my code so far, it spawns the first one in the area, and then the rest farther and farther away.
    Code:
    public void goldSpawner() {
            Location loc = getCenter();
            int dia = getDia();
            ItemStack gold = new ItemStack(Material.GOLD_INGOT, (byte) 1, (byte) 0);
            new BukkitRunnable(){
                public void run(){
                    int x = rand.nextInt(dia);
                    int z = rand.nextInt(dia);
                    Location spawnG = loc.add(x, 2.6, z);
                    getArenaWorld(arenaNum).dropItem(spawnG, gold);
                }
            }.runTaskTimer(this, 0, 160);
        }
    
    Does anyone know why this isn't working?
     
  2. Offline

    Zombie_Striker

    @flash110
    1. Does this method ever get called?
    2. What does getCenter return?
    3. You should not cast the IS parameters to bytes.
    4. You never actually state what is currently happening. What is the issue? Are there any errors?
     
  3. Offline

    flash110

    1. The method gets called on startup for testing.
    2. getCenter returns a corner location of the 5x5 area.
    3. What should I do instead?
    No Errors. It spawns the first item inside the 5x5 area, then it continuosly spawns it further away from the original 5x5 area it is supposed to be in.
     
    Last edited: Oct 8, 2016
  4. Offline

    I Al Istannen

    @flash110
    Location#add and Location#remove modify the underlying Location object.
    This means the location "loc" will get modified between each iteration.
    There are two simple fixes:
    1. Instead of "Location spawnG = loc.add(x, 2.6, z);" write "Location spawnG = loc.clone().add(x, 2.6, z);"
      But this will create a new Location object per run.
    2. After you spawned the item, remove the added numbers from the Location. So add this right after the dropItem call:
      "loc.remove(x, 2.6, z);"
    What you do is up to you.

    And I sincerly hope "getCenter" returns a clone of the location or you are in for a bad time.
     
  5. Offline

    flash110

  6. Offline

    I Al Istannen

    flash110 likes this.
Thread Status:
Not open for further replies.

Share This Page