如何使动画移动它的腿在移动? [英] How to make animation move its legs while moving?

查看:191
本文介绍了如何使动画移动它的腿在移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以现在,当你preSS去它只是在屏幕上移动时,但我也希望它移动它的腿因此它做的事情,而不只是原地踏步。如何做任何提示吗?我知道这将是移动次回合指针来回,但我不知道该怎么做。

类Stick2:

 进口的javax.swing *。
进口java.awt中的*。
java.awt.event中导入*。公共类Stick2扩展JFrame中实现的ActionListener {    //常量声明
    公共静态最终诠释FRAME_WIDTH = 500;
    私有静态最终诠释FRAME_HEIGHT = 500;
    私有静态最终诠释FRAME_X_ORIGIN = 150;
    私有静态最终诠释FRAME_Y_ORIGIN = 200;
    私有静态最终诠释BUTTON_WIDTH = 80;
    私有静态最终诠释BUTTON_HEIGHT = 30;    的JPanel buttonPanel,面板;    MovingBanner2 myBanner;
    JButton的startButton,STOPBUTTON;    螺纹THRD;
    公共静态无效的主要(字串[] args)
    {
        Stick2帧=新Stick2();
        frame.setVisible(真);
    }    公共Stick2(){
         集装箱的contentPane =的getContentPane();        //设置框架
        的setSize(FRAME_WIDTH,FRAME_HEIGHT);
        的setResizable(假);
        的setTitle(动画);
        的setLocation(FRAME_X_ORIGIN,FRAME_Y_ORIGIN);        //设置布局管理器
        contentPane.setLayout(新的BorderLayout(10,0));
        buttonPanel =新JPanel();        JButton的startButton =的新的JButton(开始);
        startButton.setSize(BUTTON_WIDTH,BUTTON_HEIGHT);
        buttonPanel.add(startButton);
        startButton.addActionListener(本);        JButton的STOPBUTTON =的新的JButton(停止);
        stopButton.setSize(BUTTON_WIDTH,BUTTON_HEIGHT);
        buttonPanel.add(STOPBUTTON);
        stopButton.addActionListener(本);        contentPane.add(buttonPanel,BorderLayout.SOUTH);        //创建一个气球
        myBanner =新MovingBanner2();
        面板= myBanner;
        panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        contentPane.add(面板,BorderLayout.CENTER);    }    公共无效的actionPerformed(ActionEvent的事件){
        JButton的clickedButton =(JButton的)event.getSource();        串buttonText = clickedButton.getText();        如果(buttonText.equals(停止)){            myBanner.stopAnimation();
            THRD = NULL;
        }
        其他{            myBanner.startAnimation();
            THRD =新主题(myBanner);
            thrd.start();
       }
    }
}

类MovingBanner2:

 类MovingBanner2继承JPanel实现Runnable {        私人诠释X;        私人布尔动画;        INT bodyX = 250;
        INT bodyY1 = 160;
        INT bodyY2 = 210;
        INT armHeight = 190;
        INT armLength = bodyX + 30;
        INT armLength1 = bodyX - 30;
        INT legY = 340;        公共MovingBanner2(){
            X = 10;
            动画= TRUE;
        }        //绘制字符串
        公共无效的paintComponent(图形G){
            super.paintComponent方法(G);            g.setColor(Color.RED);
            //g.drawString(\"I爱的Java,X,50);
            g.drawLine(bodyX + X,bodyY1,bodyX + X,bodyY2); //身体
            g.drawOval(bodyX + X - 15,bodyY1 - 40,40,40); //头
            g.drawLine(armLength + X,armHeight,armLength1 + X,armHeight); //武器
            g.drawLine(bodyX + X,bodyY2,bodyX + 20 + X,legY); //腿
            g.drawLine(bodyX + X,bodyY2,bodyX - 20 + X,legY); //腿
        }        公共无效的run(){
            而(动画){
                changeX();
                重绘();
                尝试{了Thread.sleep(100); }赶上(例外五){};
            }
        }        公共无效changeX(){            如果(X LT = Stick2.FRAME_WIDTH - 240)
                 X ++;
            别的X = 10;        }        公共无效stopAnimation(){
            动画= FALSE;
        }        公共无效startAnimation(){
            动画= TRUE;
        }
}


解决方案

有可能很多问题的答案。我能想出的最好的是基本上制定某种周期。

一个周期的时间超过该动画可以运行一个已知周期。在这个例子中,这是1秒。

然后,您需要提供一系列设置动画的通知更改周期随着时间的推移,这使得他们能够做出相应的改变对象。你也可以忽略周期为那些不需要周期的元素

的目的是提供一个单一动画引擎可以负责一气呵成更新整个状态,而不是试图使用多个线程/定时器这可能会降低系统的性能。

 进口java.awt.BorderLayout中;
进口java.awt.Color中;
进口java.awt.Container中;
进口java.awt.Dimension中;
进口java.awt.EventQueue中;
进口java.awt.Graphics;
进口java.awt.Graphics2D中;
进口java.awt.GridBagLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口java.text.NumberFormat中;
进口的java.util.ArrayList;
进口的java.util.List;
进口javax.swing.JFrame中;
进口javax.swing.JPanel中;
进口javax.swing.Timer中;
进口javax.swing.UIManager中;
进口javax.swing.UnsupportedLookAndFeelException;公共类TestAnimation06 {    公共静态无效的主要(字串[] args){
        新TestAnimation06();
    }    公共TestAnimation06(){
        EventQueue.invokeLater(新的Runnable(){
            @覆盖
            公共无效的run(){
                尝试{
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }赶上(ClassNotFoundException的| InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException前){
                }                JFrame的帧=新的JFrame(测试);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(新的BorderLayout());
                frame.add(新TestPane());
                frame.pack();
                frame.setLocationRelativeTo(NULL);
                frame.setVisible(真);
            }
        });
    }    公共接口设置动画{
        公共无效更新(浮动进度);
    }    公共类AnimationEngine {        私人列表<&设置动画GT;动画;
        私人INT CYCLETIME = 1000;
        私人长期STARTTIME = -1;        公共AnimationEngine(){
            动画=新的ArrayList<>(25);
            定时器定时器=新定时器(40,新的ActionListener(){
                @覆盖
                公共无效的actionPerformed(ActionEvent的五){
                    如果(的startTime℃,){
                        STARTTIME = System.currentTimeMillis的();
                    }
                    持续时间长= System.currentTimeMillis的() - startTime时;
                    浮动进度=(浮点)持续时间/(浮点)CYCLETIME;
                    如果(时间> = CYCLETIME){
                        进度= 1F;
                        STARTTIME = System.currentTimeMillis的();
                    }
                    对于(设置动画动画:动画){
                        animatable.update(进度);
                    }
                }
            });
            timer.setRepeats(真);
            timer.setCoalesce(真);
            timer.start();
        }        公共无效添加(设置动画动画){
            animations.add(动画);
        }    }    公共类TestPane继承JPanel {        私人AnimationEngine引擎;        公共TestPane(){
            setLayout的(NULL);
            发动机=新AnimationEngine();
            腿腿=新腿();
            沃克=新沃克(腿);
            engine.add(腿);
            engine.add(步行者);
            walker.setSize(walker.get preferredSize());
            加(步行者);
        }        @覆盖
        公共尺寸的get preferredSize(){
            返回新尺寸(200,200);
        }        @覆盖
        保护无效paintComponent(图形G){
            super.paintComponent方法(G);
            Graphics2D的G2D =(Graphics2D的)g.create();
            g2d.dispose();
        }
    }    公共类沃克继承JPanel实现可动画{        私人诠释速度= 2;        公共沃克(腿腿){
            的setLayout(新的GridBagLayout());
            加(腿);
        }        @覆盖
        公共无效更新(浮动进度){
            容器父=的getParent();
            INT宽度= parent.getWidth();
            INT XPOS =的getX()+速度;
            如果(XPOS&下; = 0){
                速度* = -1;
                XPOS = 0;
            }否则如果(XPOS +的getWidth()> =宽度){
                速度* = -1;
                XPOS =宽度 - 的getWidth();
            }
            的System.out.println(XPOS);
            的setLocation(XPOS,(parent.getHeight() - 的getHeight())/ 2);
            重绘();
        }    }    公共类腿继承JPanel实现可动画{        私人浮动frameProgress;        公共腿(){
            setOpaque(假);
        }        @覆盖
        公共尺寸的get preferredSize(){
            返回新尺寸(25,50);
        }        @覆盖
        公共无效更新(浮动进度){
            frameProgress =进展情况;
            重绘();
        }        @覆盖
        保护无效paintComponent(图形G){
            super.paintComponent方法(G);
            INT宽度=的getWidth();
            INT高度=的getHeight();            g.setColor(Color.BLACK);
            g.drawLine(宽度/ 2,0,(int)的(宽* frameProgress),高度);
            g.drawLine(宽度/ 2,0,宽度 - (int)的(宽* frameProgress),高度);
        }    }}

So right now when you press go it just moves across the screen, but I also want it to move its legs so its doing something and not just standing still. Any tips on how to do that? I know it would be moving the 2nd leg pointers back and forth but I'm not sure how to do that

Class Stick2 :

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



public class Stick2 extends JFrame implements ActionListener {

    // Declares constants 
    public static final int FRAME_WIDTH = 500;
    private static final int FRAME_HEIGHT = 500;
    private static final int FRAME_X_ORIGIN = 150;
    private static final int FRAME_Y_ORIGIN  = 200;
    private static final int BUTTON_WIDTH =80;
    private static final int BUTTON_HEIGHT = 30;

    JPanel buttonPanel, panel;

    MovingBanner2 myBanner;
    JButton startButton, stopButton;

    Thread thrd;


    public static void main(String[] args) 
    {
        Stick2 frame = new Stick2();
        frame.setVisible(true);
    }

    public Stick2(){


         Container contentPane= getContentPane();

        // Sets Frame
        setSize(FRAME_WIDTH,FRAME_HEIGHT);
        setResizable(false);
        setTitle("Animation");
        setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);

        // Sets layout manager
        contentPane.setLayout(new BorderLayout(10,0));


        buttonPanel = new JPanel();

        JButton startButton = new JButton("Start");
        startButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
        buttonPanel.add(startButton);
        startButton.addActionListener(this);

        JButton stopButton = new JButton("Stop");
        stopButton.setSize(BUTTON_WIDTH,BUTTON_HEIGHT);
        buttonPanel.add(stopButton);
        stopButton.addActionListener(this);

        contentPane.add (buttonPanel, BorderLayout.SOUTH);

        // Creates a balloon
        myBanner = new MovingBanner2();
        panel = myBanner;
        panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        contentPane.add(panel, BorderLayout.CENTER);



    }

    public void actionPerformed (ActionEvent event){
        JButton clickedButton = (JButton) event.getSource();

        String buttonText = clickedButton.getText();

        if (buttonText.equals("Stop")) {

            myBanner.stopAnimation();
            thrd = null;
        }
        else {

            myBanner.startAnimation();
            thrd = new Thread (myBanner);
            thrd.start();


       }
    }            
}

Class MovingBanner2:

class MovingBanner2 extends JPanel implements Runnable {

        private int x;

        private Boolean animate;

        int bodyX = 250;
        int bodyY1 = 160;
        int bodyY2 = 210;
        int armHeight = 190;
        int armLength = bodyX + 30;
        int armLength1 = bodyX - 30;
        int legY = 340;

        public MovingBanner2() {
            x=10;
            animate = true;
        }

        // Draws the String
        public void paintComponent (Graphics g) {
            super.paintComponent(g);

            g.setColor(Color.RED);
            //g.drawString("I love Java", x,50);
            g.drawLine(bodyX + x, bodyY1, bodyX + x, bodyY2); //body
            g.drawOval(bodyX + x - 15, bodyY1 - 40, 40, 40); //head
            g.drawLine(armLength + x,armHeight,  armLength1 + x, armHeight); //arms
            g.drawLine(bodyX + x, bodyY2, bodyX + 20 + x,legY); //leg
            g.drawLine(bodyX + x, bodyY2, bodyX - 20 + x, legY);    //leg
        }

        public void run() {
            while (animate) { 
                changeX();
                repaint();     
                try {Thread.sleep(100); } catch(Exception e){};
            }
        }



        public void changeX() {

            if (x <= Stick2.FRAME_WIDTH - 240)
                 x++;
            else x = 10;

        }

        public void stopAnimation() {
            animate = false;
        }

        public void startAnimation() {
            animate = true;
        }
}

解决方案

There are probably many answers to the question. The best I can come up with is basically to devise some kind of "cycle".

A cycle is a known period of time over which animation can run. In this example, it's 1 second.

You then need to provide a series of Animatable objects that are notified of a change to the cycle over time, which allows them to make changes accordingly. You can also ignore the cycle for those elements that don't need to cycle.

The intention is provide a single animation engine that can be responsible for updating the entire state in one go, rather then trying to use multiple threads/timers which may reduce the systems performance.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestAnimation06 {

    public static void main(String[] args) {
        new TestAnimation06();
    }

    public TestAnimation06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface Animatable {
        public void update(float progress);
    }

    public class AnimationEngine {

        private List<Animatable> animations;
        private int cycleTime = 1000;
        private long startTime = -1;

        public AnimationEngine() {
            animations = new ArrayList<>(25);
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (startTime < 0) {
                        startTime = System.currentTimeMillis();
                    }
                    long duration = System.currentTimeMillis() - startTime;
                    float progress = (float)duration / (float)cycleTime;
                    if (duration >= cycleTime) {
                        progress = 1f;
                        startTime = System.currentTimeMillis();
                    }
                    for (Animatable animatable : animations) {
                        animatable.update(progress);
                    }
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();
        }

        public void add(Animatable animatable) {
            animations.add(animatable);
        }

    }

    public class TestPane extends JPanel {

        private AnimationEngine engine;

        public TestPane() {
            setLayout(null);
            engine = new AnimationEngine();
            Legs legs = new Legs();
            Walker walker = new Walker(legs);
            engine.add(legs);
            engine.add(walker);
            walker.setSize(walker.getPreferredSize());
            add(walker);
        }

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.dispose();
        }
    }

    public class Walker extends JPanel implements Animatable {

        private int speed = 2;

        public Walker(Legs legs) {
            setLayout(new GridBagLayout());
            add(legs);
        }

        @Override
        public void update(float progress) {
            Container parent = getParent();
            int width = parent.getWidth();
            int xPos = getX() + speed;
            if (xPos <= 0) {
                speed *= -1;
                xPos = 0;
            } else if (xPos + getWidth() >= width) {
                speed *= -1;
                xPos = width - getWidth();
            }
            System.out.println(xPos);
            setLocation(xPos, (parent.getHeight() - getHeight()) / 2);
            repaint();
        }

    }

    public class Legs extends JPanel implements Animatable {

        private float frameProgress;

        public Legs() {
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(25, 50);
        }

        @Override
        public void update(float progress) {
            frameProgress = progress;
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); 
            int width = getWidth();
            int height = getHeight();

            g.setColor(Color.BLACK);
            g.drawLine(width / 2, 0, (int)(width * frameProgress), height);
            g.drawLine(width / 2, 0, width - (int)(width * frameProgress), height);
        }

    }

}

这篇关于如何使动画移动它的腿在移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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