samedi 24 avril 2021

How to make an object move randomly with a mouse click using Java?

I'm quite new to Java, but I'm trying to make a game in which when you click on an object it moves randomly on the screen. For the object I chose a circle. It also reduces the size by 25 every time it is being clicked.

Here's the mouseClicked method

    public void mouseClicked(MouseEvent event)
    {
        circleClicked++;
        xClick = event.getX();      //adds the mouse x click position to variable x Click
        yClick = event.getY();      //adds the mouse y click position to variable y click
        repaint();                  //forces applet paint method to be called again
        
        if(CIRCLE_LENGTH < 2)       //resets the game only if the CIRCLE_LENGTH is equal or less than 0 and if the left mouse button is clicked
        {
            xClick = 0;
            yClick = 0;
            misses = 0;
            CIRCLE_LENGTH = 100;
        }
    }//end mouseClicked method

and here's the if statement for when the circle is clicked

//program only executes IF statement if the user clicks on the circle       
        if((xCircle == xClick) && (yCircle == yClick))
        {   
            hitNum++;
            //Paint x and y to a random integer value between MIN_RANDOM and MAX_RANDOM
            xCircle = X_MIN_RANDOM + (int)(Math.random()*(X_MAX_RANDOM - X_MIN_RANDOM));
            yCircle = Y_MIN_RANDOM + (int)(Math.arandom()*(Y_MAX_RANDOM - Y_MIN_RANDOM));
            CIRCLE_LENGTH = CIRCLE_LENGTH - 25;   //the circle length is subsctracted by 25 everytime the user click on the circle
        }//end if

Thanks for the help!




Aucun commentaire:

Enregistrer un commentaire