Java:使用KeyPress以一定角度移动对象并更改角度 [英] Java: Moving an object at an angle and changing angle with KeyPress

查看:159
本文介绍了Java:使用KeyPress以一定角度移动对象并更改角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我想要的是矩形始终在移动,但是当您按下向左和向右箭头时,可以通过增加或减小角度来改变方向.有了此代码,square便会沿正确的方向移动,但是当我按下键时方向不会改变.

Ok, so what i want is the rectangle to always be moving, but when you press the left and right arrow is changes the direction by either increasing or decreasing the angle. With this code the sqaure moves as it should in the correct direction, but when i press the keys the direction does not change.

import java.awt.*;
import java.awt.Color;
import javax.swing.Timer;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;


public class Fields extends JPanel implements ActionListener, KeyListener{

Timer tm  = new Timer(5, this);
double x = 250, y = 250, vel = 0.2, angle = 90;

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    this.setBackground(Color.BLACK);
    g.setColor(Color.GREEN);
    g.fillRect((int)x, (int)y, 5, 5);

    tm.start();
}
public void keyTyped(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void keyReleased(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void keyPressed(KeyEvent e)
{
    if (e.getKeyCode() == 37) {angle--;}
    if (e.getKeyCode() == 39) {angle++;}
}
public void actionPerformed(ActionEvent e)
{

    x += (velX * (float)Math.cos(Math.toRadians(angle - 90)));
    y += (velX * (float)Math.sin(Math.toRadians(angle - 90)));

    repaint();
}
public Fields()
{
    this.addKeyListener(this);
}
public static void main(String[] args)
{
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(500, 500);
    Fields fi = new Fields();
    f.add(fi);
    f.setVisible(true);

}
}

推荐答案

从我的评论开始...

As started in my comments...

  • 不要在paintComponent中启动计时器,此方法会反复调用,并且可以快速连续地频繁调用.
  • 使用键绑定
  • Don't start the timer in paintComponent, this method gets called repeatedly and can be called often in quick succession.
  • Use key bindings

.

public class TestAnimation01 {

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

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

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new Fields());
                frame.setSize(400, 400);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class Fields extends JPanel implements ActionListener {

        Timer tm = new Timer(125, this);
        double x = 250, y = 250, vel = 0.2, angle = 90;
        private int velX = 4;
        private int velY = 4;

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            this.setBackground(Color.BLACK);
            g.setColor(Color.GREEN);
            g.fillRect((int) x, (int) y, 5, 5);
        }

        public void actionPerformed(ActionEvent e) {

            x += (velX * (float) Math.cos(Math.toRadians(angle - 90)));
            y += (velX * (float) Math.sin(Math.toRadians(angle - 90)));

            repaint();
        }

        public Fields() {

            setFocusable(true);

            InputMap im = getInputMap(WHEN_FOCUSED);
            ActionMap am = getActionMap();

            // left 37
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "goLeft");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "goRight");

            am.put("goLeft", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    angle--;
                    repaint();
                }
            });
            am.put("goRight", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    angle++;
                    repaint();
                }
            });

            tm.setRepeats(true);
            tm.setCoalesce(true);
            tm.start();

            requestFocusInWindow();

        }
    }
}

还有很多其他事情你还没有涉及,例如边缘条件(离开屏幕时会发生什么)和单独的x/y速度,但是我敢肯定你会解决的

There's a bunch of other things you've not covered, such as edge conditions (what happens when it leaves the screen) and individual x/y speeds, but I'm sure you'll work it out

这篇关于Java:使用KeyPress以一定角度移动对象并更改角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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