简体   繁体   English

Java:将图像移向鼠标位置

[英]Java: Move image towards mouse position

This is Bob: 这是鲍勃:

鲍勃

I already know how to make him rotate towards the mouse position thanks to this question: https://stackoverflow.com/posts/26607930/edit 由于这个问题,我已经知道如何使他旋转到鼠标位置: https : //stackoverflow.com/posts/26607930/edit


I got everything working but still can't manage to move him towards the mouse position when pressing a key. 我已完成所有工作,但按键时仍无法设法移至鼠标位置。

Here is an example: 这是一个例子:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImageFollowingMouseTest
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new ImageFollowingMousePanel());
        f.setSize(400,400);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

class ImageFollowingMousePanel extends JPanel implements MouseMotionListener
{
    private final BufferedImage image;
    private Point imagePosition = new Point(150,150);
    private double imageAngleRad = 0;

    public ImageFollowingMousePanel()
    {
        BufferedImage i = null;
        try
        {
            i = ImageIO.read(new File("6Wu0b.png"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        image = i;
        addMouseMotionListener(this);
    }

    protected void paintComponent(Graphics gr) 
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D)gr;
        g.setRenderingHint(
        RenderingHints.KEY_RENDERING, 
        RenderingHints.VALUE_RENDER_QUALITY);

        int cx = image.getWidth() / 2;
        int cy = image.getHeight() / 2;
        AffineTransform oldAT = g.getTransform();
        g.translate(cx+imagePosition.x, cy+imagePosition.y);
        g.rotate(imageAngleRad);
        g.translate(-cx, -cy);
        g.drawImage(image, 0, 0, null);
        g.setTransform(oldAT);

    }

    @Override
    public void mouseDragged(MouseEvent e)
    {
    }

    @Override
    public void mouseMoved(MouseEvent e)
    {
        double dx = e.getX() - imagePosition.getX();
        double dy = e.getY() - imagePosition.getY();
        imageAngleRad = Math.atan2(dy, dx);
        repaint();
    }
} 

Thanks in advance! 提前致谢!

The answer will depend on what you mean by "move towards"... 答案将取决于您“前进”的意思。

For example, if you want "bob" to act like a cat and chase the "mouse", then you will need some way to continuous evaluate the current mouse position and the image position. 例如,如果您希望“鲍勃”扮演猫的角色并追逐“鼠标”,那么您将需要某种方式来连续评估当前的鼠标位置和图像位置。 For this I would use a Swing Timer , its simple and doesn't violate the single thread rules of Swing, for example... 为此,我将使用Swing Timer ,它简单且不会违反Swing的单线程规则,例如...

鲍勃

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ImageFollowingMouseTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new ImageFollowingMousePanel());
        f.setSize(400, 400);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

}

class ImageFollowingMousePanel extends JPanel implements MouseMotionListener {

    private final BufferedImage image;
    private Point imagePosition = new Point(150, 150);
    private Point mousePoint;
    private double imageAngleRad = 0;

    public ImageFollowingMousePanel() {
        BufferedImage i = null;
        try {
            i = ImageIO.read(new File("6Wu0b.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        image = i;
        addMouseMotionListener(this);

        Timer timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (mousePoint != null) {

                    int centerX = imagePosition.x + (image.getWidth() / 2);
                    int centerY = imagePosition.y + (image.getHeight() / 2);

                    if (mousePoint.x != centerX) {
                        imagePosition.x += mousePoint.x < centerX ? -1 : 1;
                    }
                    if (mousePoint.y != centerY) {
                        imagePosition.y += mousePoint.y < centerY ? -1 : 1;
                    }
                    repaint();
                }
            }
        });
        timer.start();
    }

    protected void paintComponent(Graphics gr) {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D) gr;
        g.setRenderingHint(
                        RenderingHints.KEY_RENDERING,
                        RenderingHints.VALUE_RENDER_QUALITY);

        int cx = image.getWidth() / 2;
        int cy = image.getHeight() / 2;
        AffineTransform oldAT = g.getTransform();
        g.translate(cx + imagePosition.x, cy + imagePosition.y);
        g.rotate(imageAngleRad);
        g.translate(-cx, -cy);
        g.drawImage(image, 0, 0, null);
        g.setTransform(oldAT);

    }

    @Override
    public void mouseDragged(MouseEvent e) {
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        mousePoint = e.getPoint();
        double dx = e.getX() - imagePosition.getX();
        double dy = e.getY() - imagePosition.getY();
        imageAngleRad = Math.atan2(dy, dx);
        repaint();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM