I have got an application where I need to draw random number开发者_开发技巧 of points at random locations in the activity. Then I need to move those points at any direction too like steroids. How can I do that? Please see image below.
Well, if I understood you correctly, you wish to make some "asteroids" for your application.
This is not specific to Android, but you probably need to define an asteroid as an entity in your application and when you need the asteroids you just create a random number of them with random positions (you may wish to check if there is already an asteroid or other object in that position to avoid collisions).
Other than that, you just need to give each asteroid a velocity (in a 2D plane, an X and Y velocity) and update that accordingly in a loop as your application progresses.
This is a simple example, but here goes:
//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;
}
}
From here on, you would just have to create a random number of Asteroid objects, with random positions and on your application's main loop call the updatePosition and draw methods for each entity.
EDIT: Oh, and don't forget to "clear" what you've drawn at each loop cycle, so you won't see the already drawn objects in their old positions. :)
Hav look at http://www.droidnova.com/playing-with-graphics-in-android-part-iii,176.html
In onDraw method create a Random object seeding it with width and height of screen and draw points on those points as many time as you want
And onTouchevent() check the method in link change the position of these points
精彩评论