-1
我有一个移动的精灵的应用程序。我想要做的是让精灵的起始位置是随机的。我可以用'x'坐标,我只想'y'坐标是随机的。Android应用程序中的随机坐标
在下面的代码中,我设置了一个随机对象,我有一个'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
}
}
}
与往常一样,任何帮助,不胜感激。
谢谢
谢谢你。给我我需要的 –