我有一个带有精灵的应用程序。我要做的是让精灵的起始位置随机。我对'x'坐标没问题,我只想让'y'坐标随机。
在下面的代码中,我设置了一个随机对象,我有一个'y'坐标集,但我不知道如何将这两个坐标结合起来,以便它在一个随机的地方开始。理想情况下,我希望精灵每次离开屏幕时都会在一个随机的地方开始并重新开启,但首先我想让它随机启动:
package cct.mad.lab;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import java.util.Random;
public class Sprite {
//x,y position of sprite - initial position (0,50)
private int x = 0;
private int y = 50;
private int xSpeed = 80;//Horizontal increment of position (speed)
private int ySpeed = 5;// Vertical increment of position (speed)
private GameView gameView;
private Bitmap spritebmp;
//Width and Height of the Sprite image
private int bmp_width;
private int bmp_height;
// Needed for new random coordinates.
private Random random = new Random();
public Sprite(GameView gameView) {
this.gameView=gameView;
spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
R.drawable.sprite_robot);
this.bmp_width = spritebmp.getWidth();
this.bmp_height= spritebmp.getHeight();
}
//update the position of the sprite
public void update() {
x = x + xSpeed;
y = y + ySpeed;
wrapAround(); //Adjust motion of sprite.
}
public void draw(Canvas canvas) {
//Draw sprite image
canvas.drawBitmap(spritebmp, x , y, null);
}
public void wrapAround(){
//Code to wrap around
if (x < 0) x = x + gameView.getWidth(); //increment x whilst not off screen
if (x >= gameView.getWidth()){ //if gone of the right sides of screen
x = x - gameView.getWidth(); //Reset x
}
if (y < 0) y = y + gameView.getHeight();//increment y whilst not off screen
if (y >= gameView.getHeight()){//if gone of the bottom of screen
y -= gameView.getHeight();//Reset y
}
}
}
一如既往,任何帮助都非常感激。
由于
答案 0 :(得分:1)
我不确定你的问题究竟在哪里。有一个Random.nextInt(int max)
方法,所以您可以执行类似
public Sprite(GameView gameView) {
this.gameView=gameView;
spritebmp = BitmapFactory.decodeResource(gameView.getResources(),
R.drawable.sprite_robot);
this.bmp_width = spritebmp.getWidth();
this.bmp_height= spritebmp.getHeight();
this.x = random.nextInt(gameView.getWidth());
this.y = random.nextInt(gameView.getHeight());
}
这是您正在寻找的,还是在其他地方遇到麻烦?