Java Reference
In-Depth Information
Now we know how to do the
for
loop to create cows, and add them to our list
of
Cow
s. We can finally put the code in
spawnCows
:
public void
spawnCows(Location target,
int
size,
int
count) {
World world = target.getWorld();
double
x = target.getX();
double
z = target.getZ();
for
(
int
i=0; i< count; i++) {
Location loc =
new
Location(world,
x + (
Math
.random() * size),
0,
z + (
Math
.random() * size),
0,0
);
loc.setY(world.getHighestBlockAt((
int
)loc.getX(), (
int
)loc.getZ()) + 2);
Cow cow = (Cow)spawnEntityLiving(loc, EntityType.COW);
}
}
To recap: we're multiplying the random number (0..1) by the size of the square,
so that will give us a number between zero and the size of the square. We'll
use that for an x and z of the location on the square, then ask the server for
the highest block at that point and use that as the y. That's the location where
we'll spawn the new cow.
Let's compile and build it, and test it out.
I'll log in to the game and try the command
/testspawncows108
, which will spawn
eight cows within a 10×10 block from my current location.
Hey, we made some cows! They aren't very frightening, though. They're just
sitting there, as cows do. We need to get them to jump around and attack.