移动对象和定时器 [英] Moving objects and timers

查看:186
本文介绍了移动对象和定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个屏幕,说500的宽度和高度400,我有一堆形状的载体。让说的载体有例如2个不同的形状。我希望对象随机从屏幕底部弹出达到一定​​的上升后下降回落(类游戏水果忍者,这里的水果都是我的形状)。

在我的主要(视图)我有形状,而我实例化定时器的载体,添加到阵列,通过翻译功能,将它们放置在屏幕的BUTTOM。我的计时器发生在动作监听器基本上改变了翻译的形状向上移动,直到上升,然后下降,但我的问题是,所有的形状在同一时间开始考虑。

事情是这样的:

 形状F =新的Shape(新Area(新Ellipse2D.Double(0,50,50,50)));
        f.translate(0,400);
        f.timer =新的定时器(10,taskPerformer);
        f.timer.start();
        vector.add(F);
        形状F2 =新Shape(新Area(新Rectangle2D.Double(0,50,50,50)));
        f2.translate(200,400);
        f2.timer =新的定时器(10,taskPerformer);
        f2.timer.setInitialDelay(5000);
        f2.timer.start();
        vector.add(F2);

和我的动作侦听器:

 随机发生器=新的随机();
        ActionListener的taskPerformer =新的ActionListener(){
                公共无效的actionPerformed(ActionEvent的EVT){
                   //...Perform一个任务...
             对于(形状小号:model.getShapes()){
                //缩放对象使用翻译
                //一度达到提升下拉
                //转换为diffrenet屏幕的底部的一部分
                //推迟其计时器
                }
                更新();
                //基本上重绘
            }    };

我运行到所有的形状遵循相同的计时器问题,并开始在同一时间(无延迟)...

弹出

如何避免这种情况或有不同的方法,我应该尝试任何建议


解决方案

  

我希望对象随机从屏幕底部弹出达到一定​​的上升后下降回落


请参见下面的可运行的例子。我要做的就是通过一个 radomDelayedStart 图形。计时器每打勾, randomDelayedStart 减少直到它到达0,这时候要绘制的标志中提出。大部分的逻辑是在图形类的方法,这是所谓的定时取值的ActionListener 。一切都在的有一个定时完成。对于上升,我只是用一个硬$ C $ 50光盘,但你也可以通过随机提升到图形。让我知道如果您有任何疑问。我想提出的code尽可能明确。

 进口java.awt.BorderLayout中;
进口java.awt.Color中;
进口java.awt.Dimension中;
进口java.awt.Graphics;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口的java.util.ArrayList;
进口的java.util.List;
进口了java.util.Random;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JPanel中;
进口javax.swing.SwingUtilities中;
进口javax.swing.Timer中;公共类RandomShape继承JPanel {    私有静态最终诠释d_高= 500;
    私有静态最终诠释d_宽= 400;
    私有静态最终诠释增量= 8;
    私人列表<形状和GT;形状;
    私人列表<颜色和GT;颜色;
    私人定时器定时= NULL;    公共RandomShape(){
        颜色= createColorList();
        形状= createShapeList();        定时器=新定时器(30,新的ActionListener(){
            公共无效的actionPerformed(ActionEvent的五){
                对于(形状的形状:形状){
                    shape.move();
                    shape.decreaseDelay();
                    重绘();
                }
            }
        });
        JButton的开始=的新的JButton(开始);
        start.addActionListener(新的ActionListener(){
            公共无效的actionPerformed(ActionEvent的五){
                timer.start();
            }
        });
        JButton的重置=的新的JButton(重置);
        reset.addActionListener(新的ActionListener(){
            公共无效的actionPerformed(ActionEvent的五){
                形状= createShapeList();
                timer.restart();
            }
        });        的JPanel面板=新JPanel();
        panel.add(开始);
        panel.add(重置);
        的setLayout(新的BorderLayout());
        加(面板,BorderLayout.PAGE_START);
    }    @覆盖
    保护无效paintComponent(图形G){
        super.paintComponent方法(G);
        对于(形状的形状:形状){
            shape.drawShape(G);
        }
    }    @覆盖
    公共尺寸的get preferredSize(){
        返回新的Dimension(d_宽,d_高);
    }    私人列表<颜色和GT; createColorList(){
        清单<颜色和GT;名单=新的ArrayList<>();
        list.add(Color.BLUE);
        list.add(Color.GREEN);
        list.add(Color.ORANGE);
        list.add(Color.MAGENTA);
        list.add(Color.CYAN);
        list.add(Color.PINK);
        返回列表;
    }    私人列表<形状和GT; createShapeList(){
        清单<形状和GT;名单=新的ArrayList<>();
        随机随机=新的随机();
        的for(int i = 0; I< 20;我++){
            INT randXLoc = random.nextInt(d_宽);
            INT randomDelayedStart = random.nextInt(100);
            INT colorIndex = random.nextInt(co​​lors.size());
            色色= colors.get(colorIndex);
            list.add(新形状(randXLoc,randomDelayedStart,颜色));
        }        返回列表;
    }    类Shape {        INT randXLoc;
        INT Y = d_高;
        INT randomDelayedStart;
        布尔平局= FALSE;
        布尔下来= FALSE;
        色色;        公共形状(INT randXLoc,诠释randomDelayedStart,色色){
            this.randXLoc = randXLoc;
            this.randomDelayedStart = randomDelayedStart;
            this.color =颜色;
        }        公共无效drawShape(图形G){
            如果(画){
                g.setColor(颜色);
                g.fillOval(randXLoc,Y,30,30);
            }
        }        公共无效移动(){
            如果(画){
                如果(Y< = 50){
                    向下= TRUE;
                }                如果(下){
                    Y + =增量;
                }其他{
                    Ÿ - =增量;
                }
            }
        }        公共无效decreaseDelay(){
            如果(randomDelayedStart&下; = 0){
                画= TRUE;
            }其他{
                randomDelayedStart - = 1;
            }
        }    }    公共静态无效的主要(字串[] args){
        SwingUtilities.invokeLater(Runnable的新(){
            公共无效的run(){
                JFrame的帧=新的JFrame();
                frame.add(新RandomShape());
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(NULL);
                frame.setVisible(真);
            }
        });
    }
}

I have a screen with say 500 width and 400 height, and I have a vector with a bunch of shapes. let say the vector has 2 different shapes for example. I want the object to randomly pop up from the bottom of the screen reach a certain ascent and then fall back down (similar to game fruit ninja, where the fruits are my shapes).

In my main (view) I have a vector of shapes of which i instantiate the timers, add to array and place them in the buttom of the screen using the translate function. My timer takes in an action listener which basically changes the translate of the shape to move up till ascent and then down, but my problem is that all the shapes start at the same time regardless.

Something like this:

        Shape f = new Shape(new Area(new Ellipse2D.Double(0, 50, 50, 50)));   
        f.translate(0, 400);   
        f.timer = new Timer( 10 , taskPerformer);    
        f.timer.start();    
        vector.add(f);    


        Shape f2 = new Shape(new Area(new Rectangle2D.Double(0, 50, 50, 50)));    
        f2.translate(200, 400);    
        f2.timer = new Timer( 10 , taskPerformer);    
        f2.timer.setInitialDelay(5000);    
        f2.timer.start();    
        vector.add(f2);

and my action listener:

        Random generator = new Random();            
        ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                   //...Perform a task...
             for (Shape s : model.getShapes()) {
                // Scale object using translate
                // once reached ascent drop down
                // translate to diffrenet part of the bottom of the screen
                // delay its timer
                }    
                update();
                //basically repaints      
            }

    };

I'm running into problems that all shapes follow the same timer, and begin to pop up at the same time (no delay) ...

Any suggestions on how to avoid this or if there is a different approach i should try

解决方案

"I want the object to randomly pop up from the bottom of the screen reach a certain ascent and then fall back down"

See the runnable example below. What I do is pass a radomDelayedStart to the Shape. Every tick of the timer, the randomDelayedStart decreases til it reaches 0, that's when the flag to be drawn in raised. Most of the logic is in the Shape class methods, which are called in the Timers Actionlistener. Everything is done in one Timer. For the ascent, I just used a hard coded 50, but you can also pass a random ascent to the Shape. Let me know if you have any questions. I tried to made the code as clear as possible.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class RandomShape extends JPanel {

    private static final int D_HEIGHT = 500;
    private static final int D_WIDTH = 400;
    private static final int INCREMENT = 8;
    private List<Shape> shapes;
    private List<Color> colors;
    private Timer timer = null;

    public RandomShape() {
        colors = createColorList();
        shapes = createShapeList();

        timer = new Timer(30, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for (Shape shape : shapes) {
                    shape.move();
                    shape.decreaseDelay();
                    repaint();
                }
            }
        });
        JButton start = new JButton("Start");
        start.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                timer.start();
            }
        });
        JButton reset = new JButton("Reset");
        reset.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                shapes = createShapeList();
                timer.restart();
            }
        });

        JPanel panel = new JPanel();
        panel.add(start);
        panel.add(reset);
        setLayout(new BorderLayout());
        add(panel, BorderLayout.PAGE_START);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Shape shape : shapes) {
            shape.drawShape(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_WIDTH, D_HEIGHT);
    }

    private List<Color> createColorList() {
        List<Color> list = new ArrayList<>();
        list.add(Color.BLUE);
        list.add(Color.GREEN);
        list.add(Color.ORANGE);
        list.add(Color.MAGENTA);
        list.add(Color.CYAN);
        list.add(Color.PINK);
        return list;
    }

    private List<Shape> createShapeList() {
        List<Shape> list = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int randXLoc = random.nextInt(D_WIDTH);
            int randomDelayedStart = random.nextInt(100);
            int colorIndex = random.nextInt(colors.size());
            Color color = colors.get(colorIndex);
            list.add(new Shape(randXLoc, randomDelayedStart, color));
        }

        return list;
    }

    class Shape {

        int randXLoc;
        int y = D_HEIGHT;
        int randomDelayedStart;
        boolean draw = false;
        boolean down = false;
        Color color;

        public Shape(int randXLoc, int randomDelayedStart, Color color) {
            this.randXLoc = randXLoc;
            this.randomDelayedStart = randomDelayedStart;
            this.color = color;
        }

        public void drawShape(Graphics g) {
            if (draw) {
                g.setColor(color);
                g.fillOval(randXLoc, y, 30, 30);
            }
        }

        public void move() {
            if (draw) {
                if (y <= 50) {
                    down = true;
                }

                if (down) {
                    y += INCREMENT;
                } else {
                    y -= INCREMENT;
                }
            }
        }

        public void decreaseDelay() {
            if (randomDelayedStart <= 0) {
                draw = true;
            } else {
                randomDelayedStart -= 1;
            }
        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new RandomShape());
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

这篇关于移动对象和定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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