# Solved [MATH] Teleporting a player randomly in a defined radius

Discussion in 'Plugin Development' started by bobacadodl, Nov 3, 2012.

Not open for further replies.
1. Offline

In one part of my plugin, I need to teleport a player 500 to 1000 blocks randomly away from a location. Sadly, I'm not good enough at math to do this Can anyone help me out?

#1
2. Offline

### fireblast709

how about this (The only very easy method I could think of that would work in one go, in my current state of tiredness xD):
Code:java
`double areaRadius = 1000; //Or any radius you wantdouble minRadius = 500; // This would give me a radius between 500 and 1000double t = Math.random() * Math.PI;double radius = Math.random()*(areaRadius - minRadius) + minRadius;double x = Math.cos(t) * radius;double y = Math.sin(t) * radius;double z = Math.sin(t) * radius; // If you want z aswell`

#2
3. Offline

How would I include the original coordinates of the player in this? I have gotten their coordinates and want to teleport them randomly, centered on the player's coordinates. Thanks a lot for the help though!

#3
4. Offline

### fireblast709

By the means of 'translation' (as it is called in mathematics).
Code:java
`// Addition to the previousLocation to = player.getLocation().clone();to.add(x, y, z); // Its just a matter of adding the x, y and zplayer.teleport(to);`

#4
5. Offline

Code:java
` Thanks a lot! I used your code and finally got this working! :) I'm taking pre calculus next semester so hopefully i will learn how to do this math myself T_T`

#5
6. Offline

### fireblast709

My calculus course was no that bad, until the exam...

#6
7. Offline

### LucasEmanuel

You aren't going to get much randomness with that algorithm, this is how it looks if you spawned a goldblock at the position instead of teleporting a player there: How i used it:
Code:
```Location location = ((Player)sender).getLocation();

for(int i = 0 ; i < 500 ; i++) {
double minRadius = 50; // This would give me a radius between 500 and 1000
double t = Math.random() * Math.PI;
double x = Math.cos(t) * radius;
double y = Math.sin(t) * radius;
double z = Math.sin(t) * radius; // If you want z aswell

location = ((Player)sender).getLocation();

logger.debug("GOLDBLOCK! " + x + " " + y + " " + z);
}```
I would recommend something like this instead:
Code:
```Location location = ((Player)sender).getLocation();

for(int i = 0 ; i < 500 ; i++) {

int max = 100;

double x = Math.random() * (max * 2) - max;
double y = Math.random() * (max * 2) - max;
double z = Math.random() * (max * 2) - max;

location = ((Player)sender).getLocation();

logger.debug("GOLDBLOCK! " + x + " " + y + " " + z);
}
```
That ends up with this: #7
JazzaG likes this.
8. Offline

### fireblast709

LucasEmanuel true I should have used 3 random t's, then it would work perfectly fine

#8