Java-Gaming.org Hi !
Featured games (81)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (576)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1]
1  Game Development / Newbie & Debugging Questions / Re: Image not rotating around its center... on: 2012-10-06 12:01:37
Found the problem... What a stupid mistake it was haha. My getImageWidth() and getImageHeight() were not returning the correct value of 48
2  Game Development / Newbie & Debugging Questions / Image not rotating around its center... on: 2012-10-06 10:30:24
Hey all,

I am working on a new game and I have decided to try my hand at rotation. After looking at a few tutorials and learning, I came up with this:

AnimatedSprite.java - handles the actual animation,rotation and movement of sprite

http://pastebin.java-gaming.org/827c3257f21

Entity.java - just a class that handles the default attributes that all sprites will share

http://pastebin.java-gaming.org/27c353f7123

And finally MainFrame.java which just tests our code

http://pastebin.java-gaming.org/7c35f417320

The problem lies in my transform() method of AnimatedSprite.java

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
   public void transform() {
      at.setToIdentity();
      //translate to center of component
      at.translate(this.getX() +  getImageWidth() / 2,
            this.getY() + getImageHeight() / 2);
      //do rotation
      at.rotate(Math.toRadians(getFaceAngle()));
      //translate so the rotation occurs around the center of the object
      at.translate(-getImageWidth() / 2, -getImageHeight() / 2); //is something going wrong here?
   }


When I rotate the image, it rotates but it doesn't seem to rotate around the center of the image as can be seen in the screenshot below:



Any help is appreciated but I will keep working on this. Thanks!
3  Game Development / Game Mechanics / Re: Rotation Based Collision Detection on: 2012-04-25 05:07:10
Thanks antiharpist. I am a little confused by your code, do you have a demo application for it? Unsure of what you mean by rotating the map tile's :/
Any help is appreciated,
v0rtex
4  Game Development / Game Mechanics / Rotation Based Collision Detection on: 2012-04-24 18:15:17
Hey all, I am using Slick2D atm just to explore it and so far, its pretty awesome. After a couple of tutorials... I am making a 2D TopDown Zombie Shooter and whilst atm, all is okay. I really dislike how I have done collision Detection. I create a 2D Boolean array and set it to true in the following way:
1) Grab the Tiled (.tmx) map properties and check the blocked property of the tile. If its a blocked, tile. Return true else false

After this, I then do my collision detection between the player and the map, my player can rotate 360 degrees and move forward. Here is where I am having odd glitches, my player collides with the tiles correctly however if the user tries to rotate and keep moving forward, eventually the player will move through the tile.
A simple example:
o = tile, x = player

 o
 x //player moves upwards and collides with the tile

player then continues to rotate, upon 180 degree rotation the player glitches and moves through the block.

Any ideas on how to fix my collision detection? I am rather stuck with this.
Here is my code:
SimpleGame.java

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.tiled.TiledMap;

public class SimpleGame extends BasicGame {
   Image land = null;
   Image player = null;

   float playerX = 400f;
   float playerY = 300f;
   float scale = 1.0f;
   private TiledMap map;
   private Camera cam;
   private String blockedStr = "free";

   int currentBullet = 0;
   /**
    * The collision map indicating which tiles block movement - generated based
    * on tile properties
    */

   private boolean[][] blocked;
   private static final int SIZE = 32;

   public SimpleGame() {
      super("Window");
   }

   // overriden methods are the 3 methods that we will add code later to, they
   // make up our game loop
   @Override
   public void init(GameContainer gc) throws SlickException {

      map = new TiledMap("res/jungle.tmx");
      player = new Image("res/player.png"); // Note that this is Slick2D's
                                    // Image class not AWT's Image
                                    // class.

      cam = new Camera(gc, map);
      // build a collision map based on tile properties in the TileD map
      blocked = new boolean[map.getWidth()][map.getHeight()];

      for (int xAxis = 0; xAxis < map.getWidth(); xAxis++) {
         for (int yAxis = 0; yAxis < map.getHeight(); yAxis++) {
            int tileID = map.getTileId(xAxis, yAxis, 0);
            String value = map.getTileProperty(tileID, "blocked", "false");
            if (value.equals("true")) {
               blocked[xAxis][yAxis] = true;
            }
         }
      }
   }

   @Override
   public void update(GameContainer container, int delta)
         throws SlickException {
      boolean collision = false;
      Input input = container.getInput();
      float rotation = player.getRotation();
      float speed = 0.1f * delta;
      float newX = 0;
      float newY = 0;

      newX += speed * Math.sin(Math.toRadians(rotation));

      newY -= speed * Math.cos(Math.toRadians(rotation));

      if (input.isKeyDown(Input.KEY_UP)) {
         // Check all directions
         if (!(isBlocked(playerX, playerY - newY)
               || isBlocked(playerX + SIZE - 1, playerY - newY) //1 is a buffer space
               || isBlocked(playerX, playerY + SIZE + newY)
               || isBlocked(playerX + SIZE - 1, playerY + SIZE + newY)
               || isBlocked(playerX - newX, playerY)
               || isBlocked(playerX - newX, playerY + SIZE - 1)
               || isBlocked(playerX + SIZE + newX, playerY) || isBlocked(
                  playerX + SIZE + newX, playerY + SIZE - 1))) {

            // The lower the delta the slowest the sprite will animate.

            blockedStr = "Free";

            playerX += newX;
            playerY += newY;

         } else {
            collision = true;
         
         }
      }
if (collision == false) {
      if (input.isKeyDown(Input.KEY_LEFT)) {

         player.rotate(-0.2f * delta);

      }
      if (input.isKeyDown(Input.KEY_RIGHT)) {

         player.rotate(0.2f * delta);
      }
}
if (collision == true) {
   //reverse the player
   newX = 0;
   newX -= speed * Math.sin(Math.toRadians(rotation));

   newY = 0;
   newY += speed * Math.cos(Math.toRadians(rotation));
   playerY += newY;
   playerX += newX;  
}
   }

   private boolean isBlocked(float x, float y) {
      int xBlock = (int) x / SIZE;
      int yBlock = (int) y / SIZE;
      return blocked[xBlock][yBlock];
   }

   @Override
   public void render(GameContainer gc, Graphics g) throws SlickException {

      // after calculating the positions of all entities
      cam.centerOn(playerX, playerY);

      // in the render()-method
      cam.drawMap();
      cam.translateGraphics();

      // no depth in slick, images are rendered as the code executes so if we
      // render the player before the land, it will be underneath (no
      // transparency)
      player.draw(playerX, playerY);
      g.drawString("blocked:" + blockedStr, playerX - 10, playerY - 10);
   }

   public static void main(String[] args) throws SlickException {
      AppGameContainer app = new AppGameContainer(new SimpleGame());

      app.setDisplayMode(800, 600, false);
      app.start();

   }

}


Camera.java

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.tiled.TiledMap;
//Example Camera Class
public class Camera {

   protected TiledMap map;
   protected int numTilesX;
   protected int numTilesY;
   protected int mapHeight;
   protected int mapWidth;
   protected int tileWidth;
   protected int tileHeight;
   protected GameContainer gc;
   protected float cameraX;
   protected float cameraY;
   
   public Camera(GameContainer gc, TiledMap map) {
      this.map = map;
     
      this.numTilesX = map.getWidth();
      this.numTilesY = map.getHeight();
     
      this.tileWidth = map.getTileWidth();
      this.tileHeight = map.getTileHeight();
     
      this.mapHeight = this.numTilesX * this.tileWidth;
      this.mapWidth = this.numTilesY * this.tileHeight;
     
      this.gc = gc;
   }
   
   public void centerOn(float x, float y) {
      //try to set the given position as center of the camera by default
      cameraX = x - gc.getWidth()  / 2;
      cameraY = y - gc.getHeight() / 2;
     
      //if the camera is at the right or left edge lock it to prevent a black bar
      if(cameraX < 0) cameraX = 0;
      if(cameraX + gc.getWidth() > mapWidth) cameraX = mapWidth - gc.getWidth();
     
      //if the camera is at the top or bottom edge lock it to prevent a black bar
      if(cameraY < 0) cameraY = 0;
      if(cameraY + gc.getHeight() > mapHeight) cameraY = mapHeight - gc.getHeight();
   }

   public void centerOn(float x, float y, float height, float width) {
      this.centerOn(x + width / 2, y + height / 2);
   }


   public void centerOn(Shape shape) {
      this.centerOn(shape.getCenterX(), shape.getCenterY());
   }
   
 
   public void drawMap() {
      this.drawMap(0, 0);
   }
   
 
   
   public void drawMap(int offsetX, int offsetY) {
       //calculate the offset to the next tile (needed by TiledMap.render())
       int tileOffsetX = (int) - (cameraX % tileWidth);
       int tileOffsetY = (int) - (cameraY % tileHeight);
       
       //calculate the index of the leftmost tile that is being displayed
       int tileIndexX = (int) (cameraX / tileWidth);
       int tileIndexY = (int) (cameraY / tileHeight);
       
       //finally draw the section of the map on the screen
       map.render(  
             tileOffsetX + offsetX,
             tileOffsetY + offsetY,
             tileIndexX,  
             tileIndexY,
                (gc.getWidth()  - tileOffsetX) / tileWidth  + 1,
                (gc.getHeight() - tileOffsetY) / tileHeight + 1);
   }
   
   /**
    * Translates the Graphics-context to the coordinates of the map - now everything
    * can be drawn with it's NATURAL coordinates.
    */

   public void translateGraphics() {
      gc.getGraphics().translate(-cameraX, -cameraY);
   }
   /**
    * Reverses the Graphics-translation of Camera.translatesGraphics().
    * Call this before drawing HUD-elements or the like
    */

   public void untranslateGraphics() {
      gc.getGraphics().translate(cameraX, cameraY);
   }
   
}


Any help is appreciated,
v0rtex
5  Java Game APIs & Engines / Engines, Libraries and Tools / Re: Slick2D Book. on: 2012-04-22 18:54:55
I am unable to purchase the book on amazon due to credit card issues with amazon.
The book seems perfect for a beginner such as myself to Slick2D. Is there any chance you could give me an electronic copy? I can donate to you if necessary Smiley
Thanks,
v0rtex
6  Game Development / Newbie & Debugging Questions / Re: Displaying a Tile Map help needed on: 2012-02-19 19:29:24
+ rep elamre. Really awesome tutorial. Thanks for your help and the tutorial!
7  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 18:45:57
They were 76x128. OOPS Smiley
8  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 18:40:44
128 x 128. But I changed the tileSize variable:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;

import javax.swing.ImageIcon;

public class ArrayToImage {
   Image image;

   private Image wall = null;
   private Image stone = null;
   private Image Water = null;
   int x, y, temp = 0;
   private boolean imagesLoaded = false;

   public void loadImages() {
      wall = loadImage("Wall.png");
      stone = loadImage("Stone.png");
      Water = loadImage("Water.png");

      imagesLoaded = true;
   }

   private Image loadImage(String fileName) {
      return new ImageIcon(fileName).getImage();
   }

   public void drawImage(Graphics g, Image image, int x, int y) {
      g.drawImage(image, x, y, null);
   }

   public ArrayToImage() {
   }

   // This function will return an BufferedImage with all the tiles drawn on it
   public BufferedImage getMap(int[][] map) {
      loadImages();
      int largestRow = 0;
      for (int i = 0; i < map.length; i++) {
         if (map[i].length > largestRow)
            largestRow = map[i].length;
      }
      int tileSize = 128;

      BufferedImage bufferedImage = new BufferedImage(map.length * tileSize,
            largestRow * tileSize, BufferedImage.TYPE_INT_BGR);
      Graphics2D g2d = bufferedImage.createGraphics();
      g2d.setColor(Color.white);
      if (imagesLoaded) {
         for (int height = 0; height < map[0].length; height++) {
            for (int length = 0; length < map.length; length++) {
               switch (map[length][height]) {
               case 0: {
                  g2d.drawImage(Water, length * tileSize, height
                        * tileSize, null);
                  break;
               }
               case 1: {
                  g2d.drawImage(wall, length * tileSize , height
                        * tileSize, null);
                  // g2d.setColor(Color.red);
                  // g2d.fillRect(length*tileSize, height*tileSize, 32,
                  // 32);
                  break;
               }
               case 2: {
                  g2d.drawImage(stone, length * tileSize, height
                        * tileSize, null);
                  break;
               }
               }
            }
         }
         if (imagesLoaded == false) {
            System.out.println("Error Loading Images!");
         }
      }
      g2d.finalize();
      g2d.dispose();
      return bufferedImage;
   }

}
9  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 18:38:26
Sure.

http://s16.postimage.org/j78mb49xh/spacing.png
10  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 18:29:24
Uhm, one last question when I run the code, the tiles now load fine but there is huge spaces in the tiles themselves. I am unsure of how to remedy that? Any help is appreciated...
11  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 17:58:17
I don't want to sin! Ok will integrate that, thanks!
12  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 17:45:39
Any reason why in particular? Is it better resource or performance wise?
Just curious,
v0rtex
13  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 16:49:33
Got it working, for some reason returning an ImageIcon when loading the Image corrected the Image, I also added a boolean check on whether the Images were loaded correctly.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;

import javax.swing.ImageIcon;

public class ArrayToImage {
   Image image;

   private Image wall = null;
   private Image table = null;
   private Image floor = null;
   int x, y, temp = 0;
   private boolean imagesLoaded = false;

   public void loadImages() {
      wall = loadImage("wall.jpg");
      table = loadImage("Icicle.jpg");
      floor = loadImage("Floor.jpg");

      imagesLoaded = true;
   }

   private Image loadImage(String fileName) {
      return new ImageIcon(fileName).getImage();
   }

   public void drawImage(Graphics g, Image image, int x, int y) {
      g.drawImage(image, x, y, null);
   }

   public ArrayToImage() {
   }

   // This function will return an BufferedImage with all the tiles drawn on it
   public BufferedImage getMap(int[][] map) {
      loadImages();
      int largestRow = 0;
      for (int i = 0; i < map.length; i++) {
         if (map[i].length > largestRow)
            largestRow = map[i].length;
      }
      int tileSize = 32;

      BufferedImage bufferedImage = new BufferedImage(map.length * tileSize,
            largestRow * tileSize, BufferedImage.TYPE_INT_BGR);
      Graphics2D g2d = bufferedImage.createGraphics();
      g2d.setColor(Color.white);
      if (imagesLoaded) {
         for (int heigth = 0; heigth < map[0].length; heigth++) {
            for (int length = 0; length < map.length; length++) {
               switch (map[length][heigth]) {
               case 0: {
                  g2d.drawImage(floor, length * tileSize, heigth
                        * tileSize, null);
                  break;
               }
               case 1: {
                  g2d.drawImage(wall, length * tileSize, heigth
                        * tileSize, null);
                  // g2d.setColor(Color.red);
                  // g2d.fillRect(length*tileSize, heigth*tileSize, 32,
                  // 32);
                  break;
               }
               case 2: {
                  g2d.drawImage(table, length * tileSize, heigth
                        * tileSize, null);
                  break;
               }
               }
            }
         }
         if (imagesLoaded == false) {
            System.out.println("Error Loading Images!");
         }
      }
      g2d.finalize();
      g2d.dispose();
      return bufferedImage;
   }

}


Thanks again all!
14  Java Game APIs & Engines / Java 2D / Re: Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 16:21:29
I am answering here from now on as it was the site that I got the original information from. I added a JComponent and am drawing the bufferedImage to the JComponent and then adding the JComponent to a JFrame like ra4king suggested and this makes the image display correctly but the Image is still not showing up, any help is appreciated. This is really getting rather annoying Sad

Also I have confirmed (thanks to the help of elamre) that the level1.dat is being read correctly but g2d.drawImage is not adding the Images to the bufferedImage as the returned Image is simply blank?
15  Java Game APIs & Engines / Java 2D / Loading A 2D Array Into A Image. Drawing Not Working! on: 2012-02-19 12:47:14
Okay so I am trying to draw a tiled map in Java. I am currently doing the following:

  • Loading mapData from a text file (level1.dat) which is then stored into a 2D Integer Array
  • Draw a BufferedImage dependant on the map data
  • Draw the BufferedImage to my JFrame.

I have four classes:

  • ArrayToImage - Class whereby I convert the Array to the Image
  • MapToArray - Class whereby I convert the level1.dat into the 2D Array
  • Main - Class that instantiates the MainFrame
  • MainFrame - JFrame to display the Image

I think the problem is in MainFrame (Perhaps I am drawing the Image wrong?) or in ArrayToImage as the double for loop might not be working properly?

Here is the code I have worked on so far:

ArrayToImage
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;


public class ArrayToImage {
   Image image;
      //ignore this part
   private Image wall = null;
    private Image table = null;
    private Image floor = null;
      int x,y,temp=0;
      //nothing here yet
     
      public void loadImages() {
       
       wall = Toolkit.getDefaultToolkit().getImage("Tree.bmp");
          table = Toolkit.getDefaultToolkit().getImage("Icicle.bmp");
         floor = Toolkit.getDefaultToolkit().getImage("floor.bmp");
         
      }
      public ArrayToImage(){
         loadImages();
      }
      //This function will return an BufferedImage with all the tiles drawn on it
      public BufferedImage getMap(int[][] map){
         loadImages();
         BufferedImage bufferedImage = new BufferedImage(map.length*4, (map[0].length)*15, BufferedImage.TYPE_INT_BGR);
         Graphics2D g2d = bufferedImage.createGraphics();
         g2d.setColor(Color.green);
         g2d.fillRect(0, 0, map.length*4, (map[0].length)*15);
         for(int height= 0; height<map[0].length; height++){
         for(int length = 0; length<map.length; length++) {
              switch(map[length][height]){
case 0:
g2d.drawImage(floor, length*15, height*15, null);
                                break;
case 1:
g2d.drawImage(wall, length*15, height*15, null);
break;
case 2:
g2d.drawImage(table, length*15, height*15, null);
break;
}
           }
         }

         g2d.finalize();
         g2d.dispose();
         return bufferedImage;
      }
   }


MapToArray


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
public class MapToArray {

   private final String fileName;
   public int length;
   public int height;
   //simple constructor, Sets the map
   MapToArray(String fileName) {
      this.fileName = fileName;
   }
   
   //returns the 2D array of the map in INT[] []
   public int[] [] getArray() throws IOException {
      ArrayList<String> array = new ArrayList<String>();
       length = getLength();
       height = getHeight();
     
      LineNumberReader reader = new LineNumberReader (new FileReader(fileName));
      for (int i = 0; i < height; i++) {
      array.add(reader.readLine());
      }
     
      if (array.size() == 0) {
         System.out.println("Empty map");
   }
      int[][] numbers = new int [length][height]; //reserve space in memory
   int r= 0;
   //now that we have the size of our array and the data, we fill it in
   for (String s : array) {
      toArray(s, r, numbers);
      r++;
   }
   return numbers; //return map
   }
     
   //returns the map's Length
   private int getLength() throws IOException {
      int countChar = 0;
      try {
         LineNumberReader reader = new LineNumberReader (new FileReader(fileName));
      String lineRead = reader.readLine();
      int length = 0;
      while (countChar < lineRead.length()) {
         if (!(lineRead.charAt(countChar) == ',')) {
            length++;
         }
         countChar++;
      }
      reader.close();
      return length;
      } catch (IOException e) {
         throw e;
      }
   }
   
   //returns height of map (number of lines)
   public int getHeight() throws IOException {
      int height = 0;
      try {
         LineNumberReader reader = new LineNumberReader(new FileReader(fileName));
         String lineRead;
         while ((lineRead = reader.readLine()) != null) {
         }
         //loops to last line of file}
            height = reader.getLineNumber();
            reader.close();
            return height;
         
      } catch (IOException e) {
         throw e;
      }
   

   }
   
   //This function will fill an entire row with the numbers from String s.
    private void toArray(String s, int row, int[][] numbers) {
        String match = ",";
        String[] veld = s.split(match);
       
        for(int i = 0; i<veld.length;i++)
           veld[i] = veld[i].replaceAll(" ","");
       
        for (int i = 0; i < veld.length; i++) {
            try {
                numbers[i][row] = Integer.parseInt(veld[i]);
            } catch (NumberFormatException e) {
                System.out.println("Not a valid map!");
            }
        }
    }

}


MainFrame

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
import javax.swing.*;

import java.awt.*;
import java.io.IOException;
public class MainFrame extends JFrame{
   int[][] array_map1;
   MapToArray map1;
   Image bckground_1;
   ArrayToImage draw = new ArrayToImage();

public void init() throws IOException {
   map1 = new MapToArray("level1.dat"); //sets the current map
   array_map1 = map1.getArray(); // grabs the map data and stores it in a 2D integer Array.
   bckground_1 = draw.getMap(array_map1); //draws the "Map" by creating a BufferedImage dependant on the 2D Array.
   }

   MainFrame() throws IOException {
      setSize(640,480);
      setTitle("MapLoad Demo");
   init();
   setVisible(true);
   
   }
   public void paint (Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
   g2d.drawImage(bckground_1, 0, 0 ,null);
   }
   
   
   
}


Main

1  
2  
3  
4  
5  
public class Main {
   public static void main(String[] args) throws IOException {
      new MainFrame();
}
}


The problem is when I run main.java ; A 15 * 15 Image loads in the top right (only 1 tile?) so I think It might not be looping properly in ArrayToImage.java. The problem can be seen in the screenshot below:







I also think that all the Images are loading correctly as I painted one Image.
I am pretty sure that I am drawing the images incorrectly in MainFrame.java
Any help is appreciated, Thanks
v0rtex

P.S.: Here is the map Data for level1.dat

1,1,1,1,1,
1,0,0,0,1,
1,0,2,0,1,
1,0,0,0,1,
1,1,1,1,1,


Credit goes to elamre to whom provided most of the code through this tutorial.
Pages: [1]
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (38 views)
2014-10-17 03:59:02

Norakomi (29 views)
2014-10-16 15:22:06

Norakomi (24 views)
2014-10-16 15:20:20

lcass (28 views)
2014-10-15 16:18:58

TehJavaDev (56 views)
2014-10-14 00:39:48

TehJavaDev (55 views)
2014-10-14 00:35:47

TehJavaDev (46 views)
2014-10-14 00:32:37

BurntPizza (64 views)
2014-10-11 23:24:42

BurntPizza (36 views)
2014-10-11 23:10:45

BurntPizza (78 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!