如何在界限范围内获取随机数?我有最小和最大边界的X,Y和Z坐标(这是一个视频游戏)。如何获得位于这些边界内的随机坐标?
答案 0 :(得分:1)
你试过这个吗?
(Math.random() * upperLimit) + lowerLimit
答案 1 :(得分:1)
如果需要整数,请使用Random类:
import java.util.Random;
生成整数:
Random r = new Random();
r.nextInt(max - min + 1) + min; // This will return a random int between min and max
生成随机浮点数(不需要随机类)
Min + (Math.random() * (Max - Min))
答案 2 :(得分:0)
float[] getRandomVect
(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
{
//Vectors can be translated, multipled or scaled later
float[] result=new float[3];
result[0]=Math.random()*(maxX-minX)+minX;
result[1]=Math.random()*(maxY-minY)+minY;
result[2]=Math.random()*(maxZ-minZ)+minZ;
return result;
}
//later usage:
float [] randomVector= getRandomVect(2,2,3,5,5,10);
// makes vector's X between 2 and 5
// Y between 2 and 5
// Z between 3 and 10