Trouble Using MouseMotionListener

86 Views Asked by At

I just started coding just a while back. I'm trying to make a FruitNinja type game right now using a JPanel and I've pretty much done with everything(with the exception of the loops that make the game go on and the rest of the fruit/bomb animations)

So far, I've only animated the Apple.png (will get to animating other fruits once I'm done with this)

I'm trying to make a checkHit method that checks whether or not my Mouse goes over the image(slicing through the fruit), thus the MouseMotionListener that needs to be used. If the mouse does go over the fruit, I need it to disappear/move off the frame.

So how do I retrieve the coordinates from MouseMotionListener, check to see if it is within 40 pixels of my fruit and if it is, to move that fruit of the frame? If possible, not only to do that but to also play a sound when that is done.

I've got another user to help me out with this issue but I still can't quite figure it out.

import javax.swing.*;//imports JPanel class
import java.awt.*;//imports the Graphics class
import java.awt.event.*;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
//imports packages needed for the hovering


public class FruitNinja extends JPanel{


   private Image dojo;
   private Image apple;
   private Image orange;
   private Image pear;
   private Image strawberry;
   private Image banana;
   private Image bomb;

   //declares the import image variables 

  private javax.swing.Timer timer;

   private int dx, dy;

   private int vx =40;
   //velocity of the object moving in the x direction
   private int x=-10;

   private int vy=40;
   //velocity of the object moving in the y direction
   private int y=770;


   private int divide=(int)(2*Math.random())+1;//sets random number
   //determines when the fruit will bounce off

  public FruitNinja() { // a constructor to set up graphics windo
      super();
      setBackground(Color.WHITE);
      loadImage();
     dx = 25;
     dy = 25;

     timer = new javax.swing.Timer( 30, new TimerListener() );
         //interval of 10 milliseconds
     timer.start();
         //timer is a facility for threads to schedule tasks for future execution in a background thread.
   }

   private void loadImage() {
      ImageIcon ii = new ImageIcon("Dojo.jpg");
      dojo = ii.getImage();

      ImageIcon oo = new ImageIcon("Orange.ico");
      orange = oo.getImage();

      ImageIcon ss = new ImageIcon("Strawberry.png");
      strawberry = ss.getImage();

      ImageIcon bb = new ImageIcon("Banana.png");
      banana = bb.getImage();

      ImageIcon pp = new ImageIcon("Pear.png");
      pear = pp.getImage();

      ImageIcon aa = new ImageIcon("Apple.png");
      apple = aa.getImage();

      ImageIcon bo=new ImageIcon("Bomb.png");
      bomb=bo.getImage();


      //loads neccaseary images for this game


   }@Override 

   public void paintComponent(Graphics g){ // draw graphics in the panel

     super.paintComponent(g);// to make panel display correctly
     g.drawImage(dojo, 0,0, this);
  //draws out dojo
     g.drawImage(apple, x,y, this);
     g.drawImage(orange, -300,-300, this);
     g.drawImage(pear, -300,-300, this);
     g.drawImage(banana, -300,-300, this);
     g.drawImage(strawberry, -300,-300, this);
     //draws out the fruits somewhere
     g.drawImage(bomb,-300,-300,this);
     //draws out the bomb that will make the player lose

   }

  private class TimerListener implements ActionListener {

         public void actionPerformed(ActionEvent e) {

         //implements the ActionListenter


        x+=vx;   //adds velocity to the x, which makes it travel in x direction        

        if (x<0){

        vx=(-1*vx);
         //tells the velocity to change direction
        }

        y+=vy; //adds velocity to the y, which makes it travel in y direction  
        if (y>=getHeight()||y<=getHeight()/4){

        vy=(-1*vy);
         //tells the velocity to change direction
         }

        repaint(); // causes paintComponent to be called by the JVM

       }


}

   public static void main(String[] args) { 

      FruitNinja panel = new FruitNinja(); // window for drawing  
      JFrame f = new JFrame(); // the program itself
      f.setTitle("Fruit Ninja");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//when the X button is clicked, the program quits
      f.setSize(1280,800);//size of the frame
      Container pane = f.getContentPane();//pane refers to the interior of the JFrame

      FruitNinja p1 = new FruitNinja();

      pane.add(p1);//add the FacePanel object to the interior of the frame
      f.setVisible(true);

   }
}

Please let me know if I'm doing anything wrong with what I have here or/and how I can use this MouseMotionListner inside it. I'm still quite new to this, so I don't know how to retrieve the coordinates or set up the 'MouseMotionListener'. If my question is unclear, feel free to go into the comments and let me know if that is the case; I'm willing to explain the issue more thoroughly.

Thanks

Edit:

Is this the method?

      private class HandleMouse extends MouseAdapter {
   //extends MouseAdapter rather than implement Mouse Adapter
   public void mousePressed( MouseEvent e ){
        Rectangle hitBox = new Rectangle(e.getX() - 20, e.getY() - 20, 40, 40);
        Rectangle appleHitBox=new Rectangle(ax-128,ay-128,256,256);

       Area area = new Area(hitBox);
        area.intersect(new Area(appleHitBox));
        if(!area.isEmpty()){
            ax=-500;
            ay=-500;
            avx=0;
            avy=0;   
        }
        else{
            numOfMisses++;

        }
}
}

1

There are 1 best solutions below

7
On

So how do I retrieve the coordinates from MouseMotionListener,

MouseMotionListener passes a MouseEvent to the method, which contains the various properties of the event, this includes the coordinates of the event in the component coordinate context

check to see if it is within 40 pixels of my fruit and if it is

So, this is basic collision detection, there is a number of possible ways you might approach this, but because I'm lazy, I might consider using Rectangle to represent the user hit box

Rectangle hitBox = new Rectangle(e.getX() - 20, e.getY() - 20, 40, 40);

This generates a box 20 pixels around the center point of the MouseEvent.

"But why?" you ask? Because Rectangle has a number of helpful methods which can be used for collision detection including

  • intersection
  • intersects
  • union

to name a few

So given the x/y position and size of the fruit, you can simply create a second Rectangle and determine if the first hits the second

and if it is, to move that fruit off the frame?

Well, this would be a process of setting up a flag, which the "main loop" (ie your TimerListener) that tells it that the fruit has been hit, it's now up to the "main loop" to remove it from the "paint" list and setup the next object

If possible, not only to do that but to also play a sound when that is done

As a general answer, is. Once you been able to detect that a collision has occured, playing a sound is relatively simple, I'd be tempted, again, to use the "main loop" to do this as well, when it detects that a hit has occured