簡體   English   中英

如何檢測鼠標是否已左右移動(未拖動)?

[英]How to detect whether mouse has been moved(not dragged) to right or left?

我知道MouseEvent類中的getX()函數,但無法使用它檢測左或右運動。 我正在制作一個簡單的Pong游戲,其中可以通過鼠標的運動來控制球。我無法使用mouseMoved函數來確定鼠標的運動,無論它是向右還是向左移動

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

public class PongGame extends JComponent implements ActionListener,MouseMotionListener
{

    int ballX = 400;//ball's x location
    int ballY = 150;//ball's y location
    int paddleX = 0;//paddle loaction
    int ballXS = 10;//ball x speed
    int ballYS = 10;//ball y speed

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

        Timer t = new Timer(10, game);
        t.start();

        window.addMouseMotionListener(game);
    }

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

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, 800, 600);

        g.setColor(Color.GREEN);
        g.fillRect(paddleX, 580, 150, 15);

        g.setColor(Color.YELLOW);
        g.fillOval(ballX, ballY, 10, 10);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        ballX += ballXS;
        ballY += ballYS;
        //simple direction of ball to bounce around the screen
        if (ballX >= paddleX && ballX <= paddleX + 150 && ballY >= 570)
        {
            ballYS = -10;
        }
        if (ballX >= 770)
        {
            ballXS = -10;
        }
        if (ballX <= 0)
        {
            ballXS = 10;
        }
        if (ballY <= 0)
        {
            ballYS = 10;
        }
        if (ballY > 600)
        {
            ballY = 0;
            ballX = 0;
        }
        repaint();
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {

    }

    @Override
    public void mouseMoved(MouseEvent e)
    {
        paddleX = e.getX() - 75;                
        int x1 = e.getX();        
        int x2 = e.getX();
        /*here i wanted to get a left or right motion by using x1 and x2
                so that ball can be directed accordingly*/

        repaint();
    }
}
 int x = e.getX();        
 /*here i wanted to get a left or right motion by using x1 and x2
            so that ball can be directed accordingly*/
 if(x>prevx) ballXS=10; // right
 if(x<prevx) ballXS=-10; // left
 prevx=x;

根據您的整個計划,prevx是一些全局變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM