Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Getting two lines to collide

  1. #1
    Junior Member
    Join Date
    Apr 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Getting two lines to collide

    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
     
    import javax.swing.Timer;
     
    public class BouncingLinesWithSound implements ActionListener
    {
      private Random rand = new Random();
      private Timer myTimer;
      private Picture myPic;
     
      //TODO: Changed form Graphics
      private Graphics2D canvas;
     
      //TODO: Requires SoundPlayer.java to be in same project src folder as this file
      private SoundPlayer boinkSound;
     
      private static final int DRAW_WIDTH = 600;
      private static final int DRAW_HEIGHT = 600;
     
      private int x1, y1, x2, y2;
      private int x3, y3, x4, y4;
      private int speedX1, speedX2, speedY1, speedY2;
      private int speedX3, speedX4, speedY3, speedY4;
     
     
     
      //////////////////////////////////////////////////////////////////////
      // BouncingLine Constructor. This constructor:
      // 1) Creates an empty Picture Frame
      // 2) Sets the initial location, and speed of each end point of a line.
      // 3) Start the timer.
      /////////////////////////////////////////////////////////////////////
      public BouncingLinesWithSound() 
      {
        myPic = new Picture(DRAW_WIDTH, DRAW_HEIGHT);
     
        //TODO
        //If you want a Graphics2D rather than a graphics, just cast 
        //  the value returned by myPic.getOffScreenGraphics()
        canvas = (Graphics2D)myPic.getOffScreenGraphics();
     
        canvas.setColor(Color.WHITE);
        canvas.fillRect(0, 0, DRAW_WIDTH, DRAW_HEIGHT);
     
        myPic.setTitle("Bouncing Line");
     
     
        x1 = rand.nextInt(DRAW_WIDTH);
        y1 = rand.nextInt(DRAW_HEIGHT);
        x2 = rand.nextInt(DRAW_WIDTH);
        y2 = rand.nextInt(DRAW_HEIGHT);
        x3 = rand.nextInt(DRAW_WIDTH);
        y3 = rand.nextInt(DRAW_HEIGHT);
        x4 = rand.nextInt(DRAW_WIDTH);
        y4 = rand.nextInt(DRAW_HEIGHT);
     
        speedX1 = rand.nextInt(25)-12;
        speedY1 = rand.nextInt(25)-12;
        speedX2 = rand.nextInt(25)-12;
        speedY2 = rand.nextInt(25)-12;
        speedX3 = rand.nextInt(25)-12;
        speedY3 = rand.nextInt(25)-12;
        speedX4 = rand.nextInt(25)-12;
        speedY4 = rand.nextInt(25)-12;
     
     
     
     
        ////////////////////////////////////////////
        try
        {
          boinkSound = new SoundPlayer();
        }
        catch (Exception e)
        {
          System.out.println("BouncingLinesWithSound():: "+e.getMessage());
          System.exit(0);
        }
     
        myTimer = new Timer(30, this); // miliseconds
        myTimer.start();
     
      }
     
     
     
     
     
      ///////////////////////////////////////////////////////////////////////
      // Called each time the timer fires.
      // 1) Erase the current line
      // 2) Move the two end points of the line.
      // 3) Check to see if either end point moved outside the frame. If so,
      //    give that end point a random speed in the direction away from 
      //    the edge it moved off.
      // 4) Draw the line in its new location.
      ////////////////////////////////////////////////////////////////////////
      public void actionPerformed(ActionEvent arg0)
      {
     
        //Erase Line in its current location
        canvas.setColor(Color.WHITE);
        canvas.drawLine(x1, y1, x2, y2);
        canvas.drawLine(x3, y3, x4, y4);
     
        x1 += speedX1*2;
        y1 += speedY1*2;
     
        x2 += speedX2;
        y2 += speedY2;
     
        x3 += speedX3*2;
        y3 += speedY3*2;
     
        x4 += speedX4;
        y4 += speedY4;
     
        boolean hit = false;
        if (x1 < 0) 
        { speedX1 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (x1 > DRAW_WIDTH) 
        {
          speedX1 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
     
        if (y1 < 0) 
        { speedY1 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (y1 > DRAW_HEIGHT)
        { speedY1 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
     
     
        if (x2 < 0) 
        { speedX2 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (x2 > DRAW_WIDTH) 
        {
          speedX2 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
     
        if (y2 < 0) 
        { speedY2 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (y2 > DRAW_HEIGHT)
        { speedY2 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
        if (x3 < 0) 
        { speedX3 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (x3 > DRAW_WIDTH) 
        {
          speedX3 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
        if (y3 < 0) 
        { speedY3 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (y3 > DRAW_WIDTH) 
        {
          speedY3 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
        if (x4 < 0) 
        { speedX4 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (x4 > DRAW_WIDTH) 
        {
          speedX4 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
        if (y4 < 0) 
        { speedY4 = rand.nextInt(12)+1;
          hit = true;
        }
        else if (y4 > DRAW_WIDTH) 
        {
          speedY4 = -(rand.nextInt(12)+1);
          hit = true;
        }
     
     
        if (hit) boinkSound.play();
     
        //Draw Line in new location
        canvas.setColor(Color.RED);
        canvas.drawLine(x1, y1, x2, y2);
        canvas.setColor(Color.BLUE);
        canvas.drawLine(x3, y3, x4, y4);
        myPic.repaint();
     
      }
     
     
     
     
     
      /////////////////////////////////////////////////////////////////////
      // Create and run BouncingLinesWithSound
      /////////////////////////////////////////////////////////////////////
      public static void main(String[] args)
      {
        new BouncingLinesWithSound();   
      }
    }

    I'm working on this small program that has to have two lines bouncing around and colliding with the edges of the window and with themselves.
    I am really stumped on how to get the two lines to collide with each other and was hoping someone could possibly give me a push in the right direction.

    Other Classes:
    Picture.java
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Insets;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
     
     
    public class Picture extends JFrame
    { 
      public static final String VERSION = "Picture Version 2013.2.14";
     
      private int imageWidth, imageHeight;
      private BufferedImage userImage;
      private int insideLeft, insideTop;
     
      //Constructor to create an empty picture of a specified inside size
      public Picture(int insideWidth, int insideHeight)
      {
        this.setTitle(VERSION);
     
        imageWidth = insideWidth;
        imageHeight = insideHeight;
        userImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
     
        addSpaceToFrameForBoarder();
      }
     
     
      //Constructor to ask user for image file and create a Picture with that image
      public Picture()
      {
     
        String userFilePath = pickFile();
     
        userImage = loadImage(userFilePath, this);
        if (userFilePath == null)
        { imageWidth = 250;
          imageHeight = 250;
        }
        else
        { this.setTitle(userFilePath);
          imageWidth = userImage.getWidth();
          imageHeight = userImage.getHeight();
        }
        addSpaceToFrameForBoarder();
      }
     
     
     
      private void addSpaceToFrameForBoarder()
      {
        this.setSize(imageWidth, imageHeight); 
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
     
        Insets inset = this.getInsets();
        insideLeft = inset.left;
        insideTop = inset.top;
        int frameWidth = imageWidth + inset.left + inset.right;
        int frameHeight = imageHeight + inset.top + inset.bottom;
        this.setSize(frameWidth, frameHeight);
     
        System.out.println("frame size="+frameWidth+", " +frameHeight);
      }
     
     
      private static String pickFile()
      {
        String dir = System.getProperty("user.dir");
        JFileChooser fileChooser = new JFileChooser(dir);
        int returnVal = fileChooser.showOpenDialog(null);
     
        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
          File file = fileChooser.getSelectedFile();
          String imagePath = file.getPath();
          System.out.println("You selected file: ["+imagePath+"]");
          return imagePath; 
        }
     
        return null;
      }
     
     
     
     
      private static BufferedImage loadImage(String imagePath, Component window)
      {
        if (imagePath == null) return null;
     
        // Create a MediaTracker instance, to montior loading of images
        MediaTracker tracker = new MediaTracker(window);
     
        // load each image and register it, 
        // using the MediaTracker.addImage (Image, int) method. 
        // It takes as its first parameter an image, 
        // and the idcode of the image as its second parameter. 
        // The idcode can be used to inquire about the status of 
        // a particular image, rather than a group of images.
     
        // Load the image
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image loadedImage = tk.getImage(imagePath);
     
        // Register it with media tracker
        tracker.addImage(loadedImage, 1);
        try
        { tracker.waitForAll();
        }
        catch (Exception e){}
     
        int width = loadedImage.getWidth(null);
        int height = loadedImage.getHeight(null);
        BufferedImage imageBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = imageBuffer.getGraphics();
        g.drawImage(loadedImage, 0, 0, null);
     
        return imageBuffer; 
      }
     
     
     
     
      public Graphics getOffScreenGraphics()
      { return userImage.getGraphics();
      }
     
     
     
      public int getImageWidth()
      { return userImage.getWidth();
      }
     
     
     
      public int getImageHeight()
      { return userImage.getHeight();
      }
     
     
     
     
      public int getRed(int x, int y)
      {
        int rgb = userImage.getRGB(x, y);
        int red = (rgb & 0x00FF0000) >> 16;
        return red;
      }
     
      public int getGreen(int x, int y)
      {
        int rgb = userImage.getRGB(x, y);
        int green = (rgb & 0x0000FF00) >> 8;
        return green;
      }
     
     
      public int getBlue(int x, int y)
      {
        int rgb = userImage.getRGB(x, y);
        int blue = rgb & 0x000000FF;
        return blue;
      }
     
     
     
      public void setRGB(int x, int y, int r, int g, int b)
      {
        if (x<0) return;
        if (y<0) return;
        if (x>imageWidth) return;
        if (y>imageHeight) return;
        if (r<0 || g<0 || b<0) return;
        if (r>255 || g>255 || b>255) return;
     
        int rgb = (r<<16) | (g<<8) | b;
        userImage.setRGB(x, y, rgb);
      }
     
      public void setColor(int x, int y, Color c)
      {
        setRGB(x, y, c.getRed(), c.getGreen(), c.getBlue());
      }
     
      public void saveImage()
      {
        JFileChooser fileChooser = new JFileChooser();
     
        int returnValue = fileChooser.showSaveDialog(null);
     
        if (returnValue != JFileChooser.APPROVE_OPTION) return;
     
        File inputFile = fileChooser.getSelectedFile();
        String path = inputFile.getAbsolutePath();
        if ((path.endsWith(".png") == false) && (path.endsWith(".PNG") == false))
        { path = path+".png";
        }
     
        File myFile = new File(path); 
        try
        { ImageIO.write(userImage, "png", myFile);
        }
        catch (Exception e){ e.printStackTrace();}
      }
     
     
     
      public void paint(Graphics canvas)
      { 
        canvas.drawImage(userImage, insideLeft, insideTop, null);
      }

    Soundplayer.java
    import java.applet.Applet;
    import java.applet.AudioClip;
    import java.io.File;
    import java.lang.IllegalArgumentException;
    import java.net.URL;
     
    import javax.swing.JFileChooser;
     
     
    public class SoundPlayer 
    {
      private AudioClip soundEffect; // Sound player
     
      public SoundPlayer()  throws Exception
      {
        String wavfile = pickFile();
        loadClip(wavfile);
      }
     
      public SoundPlayer(String wavfile) throws Exception
      {
        if (wavfile == null)
        {
          throw new IllegalArgumentException(
              "SoundPlayer(): file is null");
        }
        // Note: if wavfile is null, then this will through a NullPointerException
        if (!wavfile.endsWith(".wav") && !wavfile.endsWith(".WAV"))
        {
          throw new IllegalArgumentException(
              "SoundPlayer(): File name must end with .wav");
        }
     
        loadClip(wavfile);
      }
     
     
     
      private void loadClip(String wavfile) throws Exception
      {
        try
        {
          File file = new File(wavfile);
          soundEffect = Applet.newAudioClip(file.toURI().toURL());
          if (soundEffect == null) throw new Exception();
          System.out.println("SoundPlayer(" + wavfile + ")");
        }
        catch (Exception e)
        {
          throw new IllegalArgumentException("SoundPlayer(): Cannot open file:"
              + wavfile);
        }
      }
     
     
     
      //=========================================================================
      // pickFile()
      //=========================================================================
      private static String pickFile()
      {
        String dir = System.getProperty("user.dir");
        JFileChooser fileChooser = new JFileChooser(dir);
        int returnVal = fileChooser.showOpenDialog(null);
     
        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
          File file = fileChooser.getSelectedFile();
          String imagePath = file.getPath();
          System.out.println("You selected file: ["+imagePath+"]");
          return imagePath; 
        }
     
        return null;
      }
     
      // Plays in a new thread
      public void play()
      { soundEffect.play(); // Play only once
     
      }
     
      public void stop()
      {
        soundEffect.stop();
      }
     
    }
    Last edited by Mertex; April 12th, 2013 at 08:31 PM. Reason: missing classes


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Getting two lines to collide

    How about defining the lines as empty rectangles. Rectangles have methods that could be useful

    The code has missing classes and will not compile for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Apr 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Getting two lines to collide

    I added the code for the other 2 files that are necessary.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Getting two lines to collide

    Start by making the data easier to work with: Create Lines with Points vs a bunch of variables: x1,y1 etc
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. PlayerObject to Collide with an Array of Objects
    By floorplay in forum Object Oriented Programming
    Replies: 2
    Last Post: March 14th, 2013, 06:27 AM
  2. PlayerObject to Collide with an Array of Objects
    By floorplay in forum Object Oriented Programming
    Replies: 0
    Last Post: March 13th, 2013, 09:41 PM
  3. Help with three lines
    By heythisgreg in forum Java Theory & Questions
    Replies: 9
    Last Post: February 17th, 2013, 05:40 PM
  4. [SOLVED] 2 Lines Stuffs.
    By Saintroi in forum What's Wrong With My Code?
    Replies: 9
    Last Post: May 11th, 2012, 08:22 AM
  5. two animated sprites collide
    By risen375 in forum AWT / Java Swing
    Replies: 1
    Last Post: June 22nd, 2011, 08:23 AM

Tags for this Thread