Solved

Java Colliding Squares

Posted on 2009-05-04
3
1,031 Views
Last Modified: 2013-11-23
Hi, i have to make a java program that has two squares that collide with each other but do not overlap.  As you can see i am using keylistenbers to make them move.  I just need some help on the logic of how to make them collide.  Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
 
public class MovingBlock extends Applet
{
	private int x = 220;
	private int y = 220;
	private int x1 = 180;
	private int y1 = 220;
	private final int BLOCK_SIZE=30;
 
	public MovingBlock()
	{
		addKeyListener(new MyKeyHandlers());
		setFocusable(true);
	}
 
	public void paint(Graphics g)
	{
		g.setColor(Color.gray);
		g.fillRect(20, 20, 400, 400); //X:20-420; Y:20-420
		g.setColor(Color.red);
		g.fillRect(x, y, BLOCK_SIZE, BLOCK_SIZE);
		g.setColor(Color.blue);
		g.fillRect(x1, y1, BLOCK_SIZE, BLOCK_SIZE);
	}
 
	//Private class for handlers that handle keys
	private class MyKeyHandlers implements KeyListener
    {
    	public void keyPressed(KeyEvent e)
		{
			final int BOUNDARY1 = 25; //Left & top boundaries to move block
			final int BOUNDARY2 = 415;//Right & bottom boundaries to move block
			int box1toprightx = x + 30
			int box1bottomrighty= y + 30
			int box1bottomlefty = 
 
			switch (e.getKeyCode())
			{
				case KeyEvent.VK_LEFT: 	if ((x >= BOUNDARY1) x = x - 5;
										break;
				case KeyEvent.VK_RIGHT: if (x + BLOCK_SIZE <= BOUNDARY2) x = x + 5;
										break;
				case KeyEvent.VK_DOWN: 	if (y + BLOCK_SIZE <= BOUNDARY2) y = y + 5;
										break;
				case KeyEvent.VK_UP: if (y >= BOUNDARY1) y = y - 5;
			}
			switch (e.getKeyCode())
			{
				case KeyEvent.VK_A: 	if (x >= BOUNDARY1) x = x - 5;
										break;
				case KeyEvent.VK_D: if (x + BLOCK_SIZE <= BOUNDARY2) x = x + 5;
										break;
				case KeyEvent.VK_S: 	if (y + BLOCK_SIZE <= BOUNDARY2) y = y + 5;
										break;
				case KeyEvent.VK_W: if (y >= BOUNDARY1) y = y - 5;
			}
 
			repaint();
		}
 
		public void keyTyped ( KeyEvent e )   {}
   	 	public void keyReleased ( KeyEvent e )   {}
	}
 
}

Open in new window

0
Comment
Question by:kshiue18
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 17

Accepted Solution

by:
Thomas4019 earned 125 total points
ID: 24300778
If you can use it, the java class Rectangle, provides some really easy methods for determing collisions between rectangles.
0
 
LVL 5

Expert Comment

by:blackfrancis75
ID: 26343818
Definitely should use the Rectangle from the 2D awt package.  Try this modified example:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
 
public class MovingBlock extends Applet
{
   Image Buffer;
   Graphics gBuffer;
   int x, y;
   boolean mouseInside, collide;
        Rectangle r1, r2;

        public void init()
        {
             Buffer=createImage(size().width,size().height);
             gBuffer=Buffer.getGraphics();

             //create 2 rectangle objects
             r1=new Rectangle(110,115,60,50);
             //we don't know the coordinates yet, so we create it
             //with a different constructor, passing only the size
             r2=new Rectangle(40,40);
        }

        public void drawStuff()
        {
             gBuffer.setColor(Color.white);
             gBuffer.fillRect(0,0,size().width,size().height);

             gBuffer.setColor(Color.red);
             gBuffer.fillRect(r1.x, r1.y, r1.width, r1.height);

             gBuffer.setColor(Color.blue);

             gBuffer.setFont(new Font("Helvetica",Font.BOLD,16));

             if(mouseInside)
                   gBuffer.fillRect(r2.x, r2.y, r2.width, r2.height);
              else
                   gBuffer.drawString("Move the mouse around!", 10, 20);

              gBuffer.setColor(Color.black);

              if(collide)
                   gBuffer.drawString("Collision!", 10, 20);
        }

        public boolean mouseEnter(Event evt,int x,int y)
        {
             mouseInside=true;
             repaint();

             return true;
        }

        public boolean mouseExit(Event evt,int x,int y)
        {
             mouseInside=false ;
             repaint();

             return true;
        }

        public boolean mouseMove(Event evt,int x,int y)
        {
             //submit the mouse coordinates to our instance variables
             this.x=x;
             this.y=y;

             //move the blue square according to mouse position
             //we use the Rectangle method "move" here
             r2.move(x-r2.width/2, y-r2.height/2);

             //check for collision here, use the "intersects" method
             //of the Rectangle class
             collide=r1.intersects(r2);

             drawStuff();

             repaint();
             return true;
        }

        public void update(Graphics g)
        {
             paint(g);
        }

        public void paint(Graphics g)
        {
             drawStuff();
             g.drawImage (Buffer,0,0, this);
        }
}

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
type mismatch (Object[] to double[] 4 41
jsp insert to database example 2 59
jboss 7.1 start up error 1 60
Why doesn't this text field show up on my Applet frame? 2 28
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question