让对象穿过屏幕,然后无限复制自己 [英] Make object go across screen and then copy itself infinitely

查看:64
本文介绍了让对象穿过屏幕,然后无限复制自己的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Game extends JComponent implements ActionListener {
    Timer t = new Timer(5, this);
    int wx;
    int rx = 10;
    int rx2 = 10;
    int carx = 10;
    int velX = 2;

    public static void main(String[] args) {
        JFrame window = new JFrame("Frogger");
        window.add(new Game());
        window.pack();
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setVisible(true);



    }
    public void actionPerformed(ActionEvent e){
        carx+=velX;
        repaint();
    }

    boolean firstFrame = true;
    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        if (firstFrame) {
            t.start();
            firstFrame = false;
        }
        g.setColor(new Color(173, 216, 230));
        g.fillRect(0, 0, 800, 600); //background
        g.setColor(Color.lightGray);
        g.fillRect(0, 525, 800, 75); //start
        g.fillRect(0, 0, 800, 30); //end
        g.setColor(Color.black);
        g.fillRect(0, 300, 800, 225); //street
        g.setColor(Color.white);

        for (int n = 0; n < 16; n++) {
            g.fillRect(rx, 450, 20, 10);
            rx += 50;
        }
        for (int n = 0; n < 16; n++) {
            g.fillRect(rx2, 375, 20, 10);
            rx2 += 50;
        }
        rx = rx2 = 10;
        while(true){
            g.fillRect(carx, 477, 60, 30);
        }

    }




}





我试图让一个物体在屏幕上移动,当它到达某一点时,程序将自我复制并在另一个物体仍然移动的情况下在屏幕上移动。我试图找出如何无限地做到这一点。我尝试使用while循环,但显然不起作用。任何帮助都表示赞赏。



I am trying to make an object move across the screen and when it gets to a certain point the program will copy itself and move across the screen with the other object still going. I am trying to figure out how to do this infinitely. I tried to use a while loop but that obviously didn't work. Any help is appreciated.

推荐答案

这只是一个创建具有定时延迟的循环或使用计时器调用重绘方法的问题。首先绘制屏幕左侧的对象。然后在每个间隔之后,在稍微向右的某个点重绘它。继续,直到物体击中右侧然后再次开始,或开始向左移动。这使它看起来像是从边缘反弹。
It is just a question of creating a loop with a timed delay, or using a timer to call the redraw mwthod. Start by drawing the object at the left side of the screen. Then after each interval you redraw it at some point slightly to the right. Continue until the object hits the right hand side then start again, or start moving it to the left. That makes it look like it bounces off the edges.


这篇关于让对象穿过屏幕,然后无限复制自己的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆