Results 1 to 18 of 18
  1. #1
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default Mouse click interrupting animation

    Hey there. I'm making this super simple 2D game while my girlfriend is out of town, and I have most of the code down for it. Essentially when you click on the bad guy (atm a red square), it disappears and 1 is added to the hit count. Well now I want to make the red squares move across the screen. I can easily achieve this using a for loop, but when I click on the squares while they're moving nothing happens.

    Frankly, I now have no idea on how to accomplish what I want to do. So here's my basic code, without any animation. Any solutions would be appreciated, along with any other comments/tips. (Yes my gf's name is robin)

    PS: files included in the attachment, and please forgive the massive code section

    Java Code:
    import java.applet.Applet;
    import java.awt.*;
    
    public class Robin extends Applet
    {
    	double clickX, clickY;
    	int numClicks, numHits;
    	Turret robin;
    	Bug[] bugList = new Bug[2];
    	
    	public void init()
    	{
    		robin = new Turret(225,300,100);
    		for(int a = 0; a < bugList.length; a++)
    			bugList[a] = new Bug(700,200 + (200 * a));
    	}
    	public void paint(Graphics g)
    	{
    		g.setColor(Color.gray);
    		g.fillRect(0,0,1000,100);
    		g.fillRect(0,500,1000,100);
    		
    		g.setColor(Color.green);
    		g.fillRect(0,100,1000,400);
    		robin.drawTurret(g);	
    		
    		g.setColor(Color.black);
    		Font font1 = new Font("Arial", Font.BOLD,12);
    		g.setFont(font1);
    		g.drawString("X Click: " + Double.toString(clickX),500,25);
    		g.drawString("Y Click: " + Double.toString(clickY),500,50);
    		g.drawString("Angle: " + Double.toString(robin.getAngle()),500,75);
    		
    		g.drawString("X Length: " + Double.toString(robin.getXLength()),400,25);
    		g.drawString("Y Length: " + Double.toString(robin.getYLength()),400,50);	
    		g.drawString("Num Clicks: " + Integer.toString(numClicks),400,75);
    		
    		g.drawString("Num Hits: " + Integer.toString(numHits),300,75);
    		
    		for(int a = 0; a < bugList.length; a++)
    			if(bugList[a].getStatus())
    				bugList[a].drawBug(g);
    			else
    				bugList[a].deleteBug(g);	
    	}
    	public boolean mouseDown(Event e, int x, int y)
    	{
    		if(x >= 225 && y > 100 && y < 500)
    		{
    			clickX = x;
    			clickY = y;
    			robin.findAngle(x,y);			
    		}
    		for(int a = 0; a < bugList.length; a++)
    			if(bugList[a].isHit(x,y) && bugList[a].getStatus())
    			{
    				numHits++;
    				bugList[a].setStatus(false);
    			}
    		numClicks++;
    		repaint();
    		return true;
    	}
    	public void update(Graphics g)
    	{
    		paint(g);
    	}
    	public static void delay(int n)
    	{
    		long startDelay = System.currentTimeMillis();
    		long endDelay = 0;
    		while (endDelay - startDelay < n)
    			endDelay = System.currentTimeMillis();	
    	}
    }
    
    import java.applet.Applet;
    import java.awt.*;
    
    public class Turret
    {
    	private double angle, centerX, centerY, barrelLength;
    	private int xLength, yLength;
    
        public Turret(int x, int y, int l) 
        {
        	centerX = x;
        	centerY = y;
        	barrelLength = l;
        	angle = 0;
        	xLength = l;
        	yLength = 0;
        }
        public void drawTurret(Graphics g)
        {
        	g.setColor(Color.gray);
    		g.fillOval((int)centerX - 50,(int)centerY - 50,100,100);
    		findXLeg(angle);
    		findYLeg(angle);
        	g.drawLine(225,300,225 + xLength,300 - yLength);		
        }
        public void findAngle(int x, int y)
    	{
    		double cartX = x - centerX;
    		double cartY = centerY - y;
    		angle = Math.toDegrees(Math.atan(cartY / cartX));
    	}
    	private void findXLeg(double a)
    	{
    		xLength = (int)(barrelLength * Math.cos(Math.toRadians(a)));
    	}
    	private void findYLeg(double a)
    	{
    		yLength = (int)(barrelLength * Math.sin(Math.toRadians(a)));
    	}
        public double getAngle()
        {
        	return angle;
        }
        public double getCenterX()
        {
        	return centerX;
        }
        public double getCenterY()
        {
        	return centerY;
        }
        public double getBarrelLength()
        {
        	return barrelLength;
        }
        public int getXLength()
        {
        	return xLength;
        }
        public int getYLength()
        {
        	return yLength;
        }    
    }
    
    import java.applet.Applet;
    import java.awt.*;
    
    public class Bug
    {
    	private int centerX, centerY;
    	private boolean alive;
    	private Rectangle body;
    	
        public Bug(int x, int y) 
        {
        	centerX = x;
        	centerY = y;
        	alive = true;
        	body = new Rectangle(centerX - 25, centerY - 25, 50, 50);
        }  
        public void drawBug(Graphics g)
        {
        	g.setColor(Color.red);
        	g.fillRect(centerX - 25, centerY - 25, 50, 50);
        } 
        public void drawBug(Graphics g, int x)
        {
        	g.setColor(Color.red);
        	g.fillRect(centerX - 25 - (50 * x), centerY - 25, 50, 50);
        	g.setColor(Color.green);
        	g.fillRect(centerX + 25 - (50 * x), centerY - 25, 50, 50);
        } 
        public void deleteBug(Graphics g)
        {
        	g.setColor(Color.green);
        	g.fillRect(centerX - 25, centerY - 25, 50, 50);
        } 
        public boolean getStatus()
        {
        	return alive;
        }
        public void setStatus(boolean a)
        {
        	alive = a;
        }
        public boolean isHit(int x, int y)
        {
        	return body.inside(x,y);
        }
    }
    Java Code:
    <APPLET CODE = "Robin.class" WIDTH=1000 HEIGHT=600>
    </APPLET>
    Attached Files Attached Files

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    See How to Write a Mouse Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
    and I'd recommend reading the API for the methods you are using/overriding, for example the mouseDown method you are overriding is deprecated as of java 1.1! And for animating, look into using a Timer (a javax.swing.Timer can be used if you decide to use Swing - which I'd recommend)

  3. #3
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Thanks for the reply. Seems my text book is a bit old then. I'll find the new methods for all the deprecated ones I'm using, write a timer, and take a look at that tutorial.

    Thanks again!

    rolledback

  4. #4
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Post

    Ok well, I really want to keep this inside an applet. So to write the swing timer I used this tutorial. Unfortunately, I cannot seem to get the timer to work, I just keep getting an error associated with the "this" in the constructor.

    Here's all the code that seems relevant to the problem. Once again, code uploaded in a .zip for your convenience.

    Java Code:
    public void init()
    {
    	appletWidth = getWidth();
    	appletHeight = getHeight();
    	accuracy = 0.0;
    	numClicks = 0;
    	numHits = 0;
    	bugList = new Bug[1];
    	robin = new Turret(50,300,100);
    	counter = 0;
    	
    	for(int a = 0; a < bugList.length; a++)
    		bugList[a] = new Bug(500,150 + (60 * a));
    				
    	virtualMem = createImage(appletWidth,appletHeight);
    	gBuffer = virtualMem.getGraphics();
    		
    	timer = new Timer(500, this);
    	timer.setInitialDelay(0);
    	timer.start(); 		
    }		
    public void actionPerformed(ActionEvent e) 
    {
    	Graphics g = getGraphics();
    	perform(g, counter);
    	counter += 10;	
    }
    public void perform(Graphics g, int x)
    {
    	if(numClicks != 0)
    		accuracy = ((double)numHits / (double)numClicks) * 100;
    	drawBugs(g, x);		
    }
    Attached Files Attached Files

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    I just keep getting an error associated with the "this" in the constructor.
    When you get an error, if you'd post the full text of the message, that is usually enough for someone to see the error.
    Please post the full text.

  6. #6
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Java Code:
    cannot find symbol
    symbol  : constructor Timer(int,Robin)
    location: class javax.swing.Timer
            timer = new Timer(500, this);

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    Read the API doc for the Timer class constructor. What data type does it take for the second argument?
    Is Robin of that data type?

    hint: You could need to use 'implements' to make it be the correct type.

  8. #8
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    hint: You could need to use 'implements' to make it be the correct type.
    Implements fixed the problem. I still can't get the mouse listener (no longer using mouseDown, now mousePressed) to work during the animation though.

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    Where is the code for the mouselistener? Does the component with the listener have the focus?

  10. #10
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Here's the code. I'm not sure what your second question means though. Probably should have mentioned this in the op, but I've only taken 2 years of high school computer science, which severely limits the concepts I am familiar to what the college board says we learn, and what I've self taught myself.

    Java Code:
    public void mousePressed(MouseEvent  e)
    	{		
    		clickX = e.getX();
    		clickY = e.getY();
    		robin.findAngle(clickX,clickY);			
    		for(int a = 0; a < bugList.length; a++)
    		{
    			if(bugList[a].isHit(clickX,clickY) && bugList[a].getStatus())
    			{
    				numHits++;
    				bugList[a].setStatus(false);
    			}
    			if(bugList[a].getCenterX() < 0)
    			{
    				bugList[a].setStatus(false);
    			}
    		}
    		numClicks++;
    		repaint();
    	}
    EDIT: updated code
    Last edited by rolledback; 06-16-2011 at 10:17 PM.

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    Time to do some more reading. Go to this site and search for mouse listener
    The Really Big Index

  12. #12
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Slowly progress is made. I read the tutorial and have since implemented the MouseListener class (took a while to remember I had to implement all of its methods).

    But two new issues have arisen unfortunately.

    1. The listener is only listening between the actionPerformed() associated with the timer
    2. as soon as I have a successful "hit", the applet freezes, and eventually turns white

    I'm going to assume there's nothing I can do about the first problem. As for the second I am not sure as to why this is even happening. Here's the up to date code.

    Java Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.Timer;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    
    public class Robin extends Applet implements MouseListener, ActionListener
    {
    	double accuracy;
    	int numClicks, numHits, appletWidth, appletHeight, counter, clickX, clickY;
    	Turret robin;
    	Bug[] bugList;
    	Image virtualMem;
    	Graphics gBuffer;
       	Timer timer;
       	
    	public void init()
    	{
    		appletWidth = getWidth();
    		appletHeight = getHeight();
    		accuracy = 0.0;
    		numClicks = 0;
    		numHits = 0;
    		bugList = new Bug[2];
    		robin = new Turret(50,300,100);
    		counter = 0;
    		addMouseListener(this);
    		
    		for(int a = 0; a < bugList.length; a++)
    			bugList[a] = new Bug(500,150 + (300 * a));
    				
    		virtualMem = createImage(appletWidth,appletHeight);
    		gBuffer = virtualMem.getGraphics();
    		
    		timer = new Timer(50, this);
    		timer.setInitialDelay(0);
    		timer.start(); 		
    	}		
    	public void actionPerformed(ActionEvent e) 
    	{
    		Graphics g = getGraphics();
       		paint(g);
       		counter += 1;	
    	}
    	public void paint(Graphics g)
    	{
    		if(numClicks != 0)
    			accuracy = ((double)numHits / (double)numClicks) * 100;
    		drawBugs(g, counter);		
    	}
    	public void drawBugs(Graphics g, int a)
    	{
    		createBackground();	
    		for(int x = 0; x < bugList.length; x++)
    			if(bugList[x].getStatus())
    			{
    				bugList[x].drawBug(gBuffer, a);
    			}
    		else
    			bugList[a].deleteBug(gBuffer, a);		
    		g.drawImage(virtualMem,0,0, this);		
    	}
    	public void createBackground()
    	{
    		gBuffer.setColor(Color.green);
    		gBuffer.fillRect(0,100,1000,400);
    	
    		gBuffer.setColor(Color.gray);
    		gBuffer.fillRect(0,0,1000,100);
    		gBuffer.fillRect(0,500,1000,100);
    		robin.drawTurret(gBuffer);
    		
    		gBuffer.setColor(Color.black);
    		Font font1 = new Font("Arial", Font.BOLD,12);		
    		gBuffer.setFont(font1);
    		gBuffer.drawString("Misses: " + Integer.toString(numClicks - numHits),10,30);
    		gBuffer.drawString("Hits: " + Integer.toString(numHits),10,45);
    		gBuffer.drawString("Accuracy: " + Integer.toString((int)accuracy) + "%",10,60);
    	}
    	public void update(Graphics g)
    	{
    		paint(g);
    	}
    	public void mouseClicked(MouseEvent e) 
        {
        	clickX = e.getX();
    		clickY = e.getY();
    		robin.findAngle(clickX,clickY);			
    		for(int a = 0; a < bugList.length; a++)
    		{
    			if(bugList[a].isHit(clickX,clickY) && bugList[a].getStatus())
    			{
    				numHits++;
    				bugList[a].setStatus(false);
    			}
    			if(bugList[a].getCenterX() < 0)
    			{
    				bugList[a].setStatus(false);
    			}
    		}
    		numClicks++;
    		repaint();
        } 
        public void mousePressed(MouseEvent e) {}    
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {} 
    }

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    You're not supposed to call paint() directly. You call repaint() and the system will call paint later with the correct Graphics object.

  14. #14
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Changed to the paint(g) to repaint(), but the Applet still freezes when a red square is clicked.

  15. #15
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    Add some printlns to the code to show where the execution flow is going. The output should help determine the problem. Add one to each method to show when it starts executing. If you are in a loop the output will show that.

  16. #16
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Found it. Was getting an out of bounds in drawBugs() which should have read like this:

    Java Code:
    public void drawBugs(Graphics g, int a)
    	{
    		createBackground();	
    		for(int x = 0; x < bugList.length; x++)
    			if(bugList[x].getStatus())
    			{
    				bugList[x].drawBug(gBuffer, a);
    			}
    		else
    			bugList[x].deleteBug(gBuffer, a);		
    		g.drawImage(virtualMem,0,0, this);		
    	}
    The [a] was giving an out of bounds (if I had configured jcreator to show output in a cmd window when running an applet I would have seen this much sooner). An error I had corrected earlier in the if statement, but neglected to correct in the else. So do you have any suggestions for what would be good numbers for the timer so the blocks move at a decent speed, but when you click there's a high chance the listener is listening? (does that make sense?)
    Last edited by rolledback; 06-16-2011 at 11:54 PM.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,877
    Rep Power
    25

    Default

    good numbers for the timer so the blocks move at a decent speed
    Try different values until you find one that works.

  18. #18
    rolledback is offline Member
    Join Date
    Jun 2011
    Posts
    15
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    Try different values until you find one that works.
    Will do. Thanks for all the help today Norm. I don't think I'll have any other questions today, but if I do I'll be sure to post in this thread. And once I'm done I'll upload the files. Thanks again.

Similar Threads

  1. Mouse Click changes Color of Rectangle
    By DocIcarus in forum New To Java
    Replies: 1
    Last Post: 11-23-2010, 02:53 PM
  2. Using an EMG signal to create a mouse click
    By cmc419 in forum New To Java
    Replies: 1
    Last Post: 03-27-2009, 06:38 PM
  3. mouse click do not work after repaint
    By nobody in forum Java 2D
    Replies: 8
    Last Post: 12-07-2008, 05:43 PM
  4. mouse click alert
    By amir in forum AWT / Swing
    Replies: 1
    Last Post: 08-05-2008, 11:42 PM
  5. Problem in mouse click n repaint
    By Preethi in forum New To Java
    Replies: 4
    Last Post: 07-04-2008, 12:16 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •