我正在创建一个应用程序,其中气泡在屏幕上反弹,您会得到弹出气泡的点,然后重新生成它们。
除了用于控制气泡在屏幕上运动的速度和方向整数以外,每个气泡都是完全相同的。
到目前为止,我只有一个ImageView称为“气泡”。然后,我运行我创建的randoms()方法。randoms()
的代码:
public void randoms(){
ySpeedRand = new Random();
xSpeedRand = new Random();
yPolarityRand = new Random();
xPolarityRand = new Random();
ySpeed = ySpeedRand.nextInt(5) + 4;
xSpeed = xSpeedRand.nextInt(5) + 4;
yPolarity = yPolarityRand.nextInt(3) + 1;
xPolarity = xPolarityRand.nextInt(3) + 1;
if (xPolarity == 1){
xSpeed*=-1;
}
if (yPolarity == 2){
ySpeed*=-1;
}
}
然后,我有一个侦听器检查气泡何时被点击,然后使其不可见,重新运行randoms()块,然后使其可见。
这是控制气泡位置的处理程序:
final Handler handler = new Handler();
Runnable run = new Runnable() {
@Override
public void run() {
bubble.setX(bubble.getX()+xSpeed);
bubble.setY(bubble.getY()+ySpeed);
handler.postDelayed(this, 5);
}
};handler.post(run);
我使用以下代码检查气泡是否仍在屏幕上:
final Handler checkHandler = new Handler();
Runnable check = new Runnable() {
@Override
public void run() {
if (bubble.getX()>SCREEN_WIDTH-bubble.getWidth()/2){xSpeed*=-1;}
if (bubble.getX()<0){xSpeed*=-1;}
if (bubble.getY()>SCREEN_HEIGHT-bubble.getHeight()){ySpeed*=-1;}
if (bubble.getY()<bubble.getHeight()/2+barHeight+actionBorder.getHeight()){ySpeed*=-1;}
handler.postDelayed(this, 50);
}
};checkHandler.post(check);
有没有简单的方法可以简单地扩展此系统,因此我可以调用方法createbubble(),然后让新气泡具有与旧气泡完全相同的属性,但使用新生成的随机数?
我被100%卡住了,找不到任何东西。任何帮助都非常感谢!
最佳答案
我对您的问题有点困惑。不知道为什么要尝试使用ImageView
。以此为目标:
创建一个会产生泡泡并可以弹出的游戏
弹出时,气泡应移至屏幕上的随机空间
当气泡离开屏幕时,请反转方向。
我至少会进行以下课程:
启动器,存储main()方法并运行游戏循环
窗口,在extends Canvas
中,您将在其中设置JFrame
控制,每次启动器完成一个循环时都要计算物理量
实体,一个抽象的java对象
气泡
这是制作游戏循环的一种方法:http://www.java-gaming.org/index.php?topic=24220.0
这是一个如何制作JFrame的例子:
import java.awt.Canvas;
import javax.swing.JFrame;
public class Window extends Canvas{
public Window(Launcher launcher){
JFrame frame = new JFrame("Title");
frame.setSize(700,500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(launcher);
frame.setVisible(true);
launcher.setFrame(frame);
}
}
为了跟踪气泡,我将在Control类中声明并初始化
LinkedList<>
。要创建气泡,请在Control中运行以下操作:public class Control{
public LinkedList<Entity> entity = new LinkedList<Entity>();
Random rand = new Random();
public Control(){
//You will have to define these constants in the Launcher class
entity.add(
rand.nextInt(Launcher.WINDOW_WIDTH),
rand.nextInt(Launcher.WINDOW_HEIGHT)
);
}
//Called every time Launcher completes a game loop
tick(){
for(int i=0; i<entity.size(); i++){
entity.get(i).tick();
}
}
}
在实体类中:
public abstract class Entity{
protected double x;
protected double y;
public Entity(int x, int y){
this.x = x;
this.y = y;
}
public abstract void tick();
public abstract void render(Graphics g);
//Getters and setters here ...
}
在Bubble类中:
public class Bubble extends Entity{
public double x = 0;
public double y = 0;
public Bubble(int x, int y){
super(x,y);
}
public void tick(){
//Physics go here
}
public void render(){
//Graphics functions go here
}
}
如果没有任何道理,请告诉我,我将作更详细的解释,甚至考虑到任务的简单性,甚至进一步为您制作整个程序。