我有一个应用程序,我需要在 Activity 的随机位置绘制随机数量的点。然后我需要像类固醇一样向任何方向移动这些点。我怎样才能做到这一点?请参见下图。
最佳答案
好吧,如果我没理解错的话,您希望为您的应用制作一些“小行星”。
这不是 Android 特有的,但您可能需要在您的应用程序中将小行星定义为一个实体,当您需要小行星时,您只需创建随机数量的小行星和随机位置(您可能希望检查是否有已经有小行星或其他物体处于该位置以避免碰撞)。
除此之外,您只需要为每颗小行星指定一个速度(在 2D 平面中,X 和 Y 速度)并随着应用程序的进行相应地循环更新。
这是一个简单的例子,但是这里是:
//To make things easier, let's assume you have an Entity class, from which every game object is inherited
public abstract class Entity {
// Fields used to know object position
private float x;
private float y;
// Fields used to calculate object motion
private float x_speed;
private float y_speed;
...
// You would probably have a generic method to draw every entity - details are not relevant to your question, but you should draw the object taking it's x and y coordinates into account here
public void draw() { ... }
// Generic function to update the object's position regarding its speed
public void updatePosition() {
this.x += this.x_speed;
this.y += this.y_speed;
}
...
}
//Let's say you have an Asteroid class, which represents each asteroid
public class Asteroid extends Entity {
// Just add a constructor to set it's initial position and speed
public Asteroid(float initial_x, float initial_y, float ini_x_speed, float ini_y_speed) {
this.x = initial_x;
this.y = initial_y;
this.x_speed = ini_x_speed;
this.y_speed = ini_y_speed;
}
}
从这里开始,您只需创建随机数量的 Asteroid 对象,它们具有随机位置,并在应用程序的主循环中为每个实体调用 updatePosition 和 draw 方法。
编辑:哦,不要忘记在每个循环周期“清除”您绘制的内容,这样您就不会在它们的旧位置看到已经绘制的对象。 :)
关于android - 在随机点画圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5028218/