Advertisement
boxglue

MyImage class

Apr 27th, 2020
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. package bouncer;
  2. import java.awt.Rectangle;
  3. import java.awt.image.BufferedImage;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import javax.imageio.ImageIO;
  7.  
  8.  
  9. //NOTE: This class requires BouncingImages.java
  10.  
  11. /* This class combines an image with a rectangle
  12.  * which allows for easy movement and collision detection
  13.  */
  14. class MyImage extends Rectangle{
  15.     //this gives it an x,y,width,height
  16.    
  17.     BufferedImage image;
  18.    
  19.     //these are the speeds of movement
  20.     int dx=1;
  21.     int dy=1;
  22.    
  23.     MyImage(String filename) {
  24.         //load the image
  25.         try {
  26.             image = ImageIO.read(new File(filename));
  27.         } catch (IOException e) {
  28.             System.out.println("ERROR: image file \"" + filename + "\" not found");
  29.             //e.printStackTrace();
  30.             System.exit(0);
  31.         }
  32.         //image = (BufferedImage) new ImageIcon(filename).getImage();   Does not work with BufferedImage
  33.         width = image.getWidth(null);
  34.         height = image.getHeight(null);
  35.     }
  36.    
  37.     void moveImage(){
  38.         x += dx;
  39.         y += dy;
  40.         if (x < 0 && dx < 0) {
  41.             x = 0;
  42.             dx = -dx;
  43.         }
  44.         if (y < 0 && dy < 0) {
  45.             y = 0;
  46.             dy = -dy;
  47.         }
  48.         if(x + width > BouncingImages.WINW && dx > 0) {
  49.             x = BouncingImages.WINW-width;
  50.             dx = -dx;
  51.         }
  52.         if(y + height > BouncingImages.WINH && dy > 0) {
  53.             y = BouncingImages.WINH-height;
  54.             dy = -dy;
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement