0
所以我想创造一个游戏,这是我第一次。我的游戏是一款2D侧面卷轴,关于避开流星的空间玩家。我已经成功设法让流星在屏幕上随机产生x和y轴,并在屏幕通过后重新定位。LibGDX - 如何在相距一定距离处产生物体?
但是我现在面临的问题是有时流星的产卵会聚集在一起,我不想要。我如何让流星在相距一定距离的地方产卵,这样它们就不会聚集在一起。我找不到任何好的教程,或者任何人都可以指出我正确的方向。以下是我的代码。
流星类
public class Meteors {
private Texture bigMeteor;
private Vector2 posBigMeteor;
private Random yrand;
//Constructor
public Meteors(float x){
bigMeteor = new Texture("meteor.png");
yrand = new Random();
//Spawn location of meteor
posBigMeteor = new Vector2(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
}
public Texture getBigMeteor() {
return bigMeteor;
}
public Vector2 getPosBigMeteor() {
return posBigMeteor;
}
//Reposition the meteors
public void reposition(float x){
posBigMeteor.set(x, yrand.nextInt(AstroDemo.HEIGHT/2 - bigMeteor.getHeight()));
}
}
PlayState类
public class PlayState extends State {
//Total meteor count on screen
private static final int METEOR_COUNT = 8;
private Naught naught;
private Texture bg;
private Random xrand;
private Array <Meteors> meteors;
public PlayState(GameStateManager gsm) {
super(gsm);
//Starting co-ordinates of main character (Naught)
naught = new Naught(50, 100);
//Setting viewport of the camera
cam.setToOrtho(false, AstroDemo.WIDTH/2, AstroDemo.HEIGHT/2);
bg = new Texture("bg.png");
xrand = new Random();
meteors = new Array <Meteors>();
//Spawn meteors randomly off screen
for (int i = 1; i <= METEOR_COUNT; i++){
meteors.add(new Meteors(AstroDemo.WIDTH/2 + (xrand.nextInt(300))));
}
}
@Override
protected void handleInput() {
//If screen/mouse is held
if(Gdx.input.isTouched()){
//Main Character jumps/flys
naught.jump();
}
}
@Override
public void update(float dt) {
handleInput();
naught.update(dt);
//If meteors are left side of the screen, re-position to the right side of the screen
for(Meteors meteor : meteors){
if (cam.position.x - (cam.viewportWidth/2) > meteor.getPosBigMeteor().x + meteor.getBigMeteor().getWidth()){
meteor.reposition(meteor.getPosBigMeteor().x + (AstroDemo.WIDTH/2 + 20 + (xrand.nextInt(300))));
}
}
cam.position.x = naught.getPosition().x + 80;
cam.update();
}
@Override
public void render(SpriteBatch sb) {
//Adjust the spritebatch for co-ordinate system in relation to camera
sb.setProjectionMatrix(cam.combined);
sb.begin();
//Draw background where the camera is
sb.draw(bg, cam.position.x - (cam.viewportWidth/2), 0);
sb.draw(naught.getTexture(), naught.getPosition().x, naught.getPosition().y);
for (Meteors meteor : meteors) {
sb.draw(meteor.getBigMeteor(), meteor.getPosBigMeteor().x, meteor.getPosBigMeteor().y);
}
sb.end();
}
@Override
public void dispose() {
}
}
在计算距离或仅计算x轴时,是否要考虑x和y轴?这[post](http://stackoverflow.com/questions/929773/calculating-the-distance-between-two-points)解释了如何计算,你可以使用这些信息来解决你的问题。 – Squiddie
@Squiddie Yh我仍然想要考虑x轴和y轴,所以我希望它们随机产卵但不能彼此重叠。 从阅读帖子我认为我明白该怎么做,但帖子提到两点,而不是两个对象,我相信半径参与,我正在努力与数学,并把这些数学成java/libgdx语言。 – user218130
我相信你的两个对象包含坐标吗?这些都是要点。我想你的对象有一个'x'和一个'width',以获得对象中间的坐标,只需执行'x + width/2',和y和height一样。使用这些点。 – Squiddie