Hi,

I've been trying to learn how to do collision between a sprite and a tile for a while, so I've been testing this point collision I found from a Java book. But for some reason, the tile's images can't be drawn onto the screen. Any Ideas or thoughts to fix this?

Here are the important source codes:


Smiley

public class Smiley extends Sprite {

    public int jCount = 0;
    public float g = .002f;

    public Smiley() {
        i = new ImageIcon(this.getClass().getResource("/extrememario/smiley/sprites/Face1.PNG")).getImage();
        x = 250;
        y = 250;
    }

    public void update() {
        moveX();
        moveY();
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_RIGHT) {
            setDx(6);
        } else if (keyCode == KeyEvent.VK_LEFT) {
            setDx(-6);
        }
        if (keyCode == KeyEvent.VK_UP) {
            if (jCount == 0) {
                setDy(-3);
                jCount = 1;
                if (y < 150 && jCount == 1) {
                    setDy(3);
                }
            } else if (y < 150 && jCount == 1) {
                setDy(3);
            } else if (jCount == 1 && y >= 250) {
                jCount = 0;
            }

        }
    }

    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_RIGHT) {
            setDx(0);
        } else if (keyCode == KeyEvent.VK_LEFT) {
            setDx(0);
        }

        if (keyCode == KeyEvent.VK_UP) {
            setDy(3);
        }

    }

    public void keyTyped(KeyEvent e) {
    }

    public Rectangle colRec() {
        return new Rectangle(Math.round(x), Math.round(y), getWidth(), getHeight() + 3);
    }

    public boolean collisionTRight(Rectangle r) {
        if (x >= r.x + r.width) {
            if (r.intersects(colRec())) {
                x = r.x + r.width;
                System.out.println("right");
                return true;
            } else if (!r.intersects(colRec())) {
                return false;
            }
        }

        return false;
    }

    public boolean collisionTLeft(Rectangle r) {
        if (x <= r.x) {
            if (r.intersects(colRec())) {
                x = r.x - colRec().width;
                System.out.println("left");
                return true;
            } else if (!r.intersects(colRec())) {
                return false;
            }
        }

        return false;
    }

    public boolean collisionTTop(Rectangle r) {
        //if (y >= r.y) {
        if (r.intersects(colRec())) {
            y = r.y - colRec().height;
            System.out.println("top");
            return true;
        } else if (!r.intersects(colRec())) {
            return false;
        }
        //}
        return false;
    }

    public boolean collisionTBottom(Rectangle r) {
        //if (y <= r.y + r.getHeight()) {
        if (r.intersects(colRec())) {
            y = r.y + r.height;
            System.out.println("bottom");
            return true;
        } else if (!r.intersects(colRec())) {
            return false;
        }
        //}

        return false;
    }

    public float moveX() {
        return x = x + getDx();
    }

    public float moveY() {
        return y = y + getDy();
    }

    public Image getFrame() {
        return getImage();
    }
}

Level

public class Level extends TileMap{

    public ArrayList<Image> tilesArray = new ArrayList();
    public Point pointCache = new Point();

    public Level(){
        super(16,16);
    }
    public synchronized TileMap loadMap(URL url) throws IOException {        
        ArrayList lines = new ArrayList();
        int width = 16;
        int height = 16;
        File f;
        try{
           f = new File(url.toURI());
        }catch(URISyntaxException e){
           f = new File(url.getPath());
        }
        //BufferedReader reads text files
        BufferedReader reader = new BufferedReader(new FileReader(f));
        while (true) {
            String line = reader.readLine();
            //no more lines to read
            if (line == null) {
                reader.close();
                break;
            }
            //Add lines, except with comments(#)
            if (!line.startsWith("#")) {
                lines.add(line);
                width = Math.max(width, line.length());
            }
        }

        height = lines.size();
        TileMap newMap = new TileMap(width, height);
        for (int y = 0; y < height; y++) {
            String line = (String) lines.get(y);
            for (int x = 0; x < line.length(); x++) {
                char ch = line.charAt(x);

                //check if the char represents tile           
                if (ch =='1') {
                    newMap.setTile(x, y, new ImageIcon(this.getClass().getResource("/extrememario/levels/normal/1.png")).getImage());
                    System.out.println(newMap.getHeight());
                }
            }
        }

        return newMap;
    }
    public void drawLevel(Graphics g){       
        for (int y = 0; y < this.getHeight(); y ++){
            for(int x = 0; x < this.getWidth(); x ++){
                Image image = this.getTile(x, y);
                if(image != null){
                    g.drawImage(image, TileMapRender.tilesToPixels(x), TileMapRender.tilesToPixels(y), null);
                }
            }
        }
    }

    public Point getTileCollision(Sprite sprite, float newX, float newY) {
        float fromX = Math.min(sprite.getX(), newX);
        float fromY = Math.min(sprite.getY(), newY);
        float toX = Math.min(sprite.getX(), newX);
        float toY = Math.min(sprite.getY(), newY);

        int fromTileX = TileMapRender.pixelsToTiles(fromX);
        int fromTileY = TileMapRender.pixelsToTiles(fromY);
        int toTileX = TileMapRender.pixelsToTiles(toX + sprite.getWidth() - 1);
        int toTileY = TileMapRender.pixelsToTiles(toY + sprite.getHeight() - 1);

        for (int x = fromTileX; x <= toTileX; x++) {
            for (int y = fromTileY; y <= toTileY; y++) {
                if (x < 0 || x > this.getWidth()
                        || this.getTile(x, y) != null) {
                    pointCache.setLocation(x, y);
                    return pointCache;

                }
            }
        }
        return null;
    }
}

TileMap

import extrememario.Sprite;
import java.awt.Image;
import java.util.Iterator;
import java.util.LinkedList;

    public class TileMap {

        public Image[][] tiles;
        public LinkedList sprites;

        public TileMap(int w, int h) {
            tiles = new Image[w][h];
            sprites = new LinkedList();
        }

        public int getWidth() {
            return tiles.length;
        }

        public int getHeight() {
            return tiles[0].length;
        }

        public Image getTile(int x, int y) {
            if (x < 0 || x >= getWidth()
                    || y < 0 || y >= getHeight()) {
                return null;
            } else {
                return tiles[x][y];
            }
        }

        public void setTile(int x, int y, Image tile) {
            tiles[x][y] = tile;
        }

        public void addSprite(Sprite sprite) {
            sprites.add(sprite);
        }

        public void removeSprite(Sprite sprite) {
            sprites.remove(sprite);
        }

        public Iterator getSprites() {
            return sprites.iterator();
        }
    }

TileMapRender

public class TileMapRender {
    
    public static int TileSize = 16;
    //the size in bits of the tile
    //Math.pow(2,Tile_Size_Bits) = TileSize
    public static int TileSizeBits = 4;
    
    public static int pixelsToTiles(float pixels){
        return pixelsToTiles(Math.round(pixels));
    }
    
    public static int pixelsToTiles(int pixels){
        return pixels >> TileSizeBits;
    }
    
    public static int tilesToPixels(int numTiles){
    
        return numTiles << TileSizeBits;
    }
    
}

Test

public class Test extends Level {

    public Test(){
        getMap();
    }

    public void getMap(){
        try {
            this.loadMap(this.getClass().getResource("/extrememario/levels/testlevel/Map.txt"));
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }
}

MainConfig

public class MainConfig extends JPanel implements Runnable {

    public Smiley mario;
    public Thread mainLoop;
    public Test test = new Test();

    public MainConfig() {
        mario = new Smiley();
        setFocusable(true);
        addKeyListener(new KL());
    }

    @Override
    public void addNotify() {
        super.addNotify();
        mainLoop = new Thread(this);
        mainLoop.start();
    }
    public Image bg = new ImageIcon(this.getClass().getResource("/extrememario/BackgroundDemoStage.png")).getImage();

    @Override
    public void paint(Graphics g) {
        g.drawImage(bg, 0, 0, null);
        g.drawImage(mario.getFrame(),Math.round(mario.moveX()), Math.round(mario.moveY()), null);
        test.drawLevel(g);
        g.dispose();
    }

    public class KL extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent e) {
            mario.keyPressed(e);
        }

        @Override
        public void keyReleased(KeyEvent e) {
            mario.keyReleased(e);
        }
    }

    public void updateCollisionPlayer(){
        
    }
    @Override
    public void run() {
        long lastTime = System.currentTimeMillis();
        while (true) {
            long nowTime = System.currentTimeMillis();
            long timePassed = nowTime - lastTime;
            lastTime = nowTime;
            mario.update();
            repaint();
            try {
                Thread.sleep(20);
            } catch (Exception e) {
            }
        }

    }
}

Sprite

public class Sprite {

    public float x, y, dx, dy;
    public Image i;

    public int getWidth() {
        return i.getWidth(null);
    }

    public int getHeight() {
        return i.getHeight(null);
    }

    public float getX() {
        return x - getWidth() / 2;
    }

    public float getY() {
        return y - getHeight() / 2;
    }

    public float getDy() {
        return dy;
    }

    public float getDx() {
        return dx;
    }

    public void setDy(float my) {
        dy = my;
    }

    public void setDx(float mx) {
        dx = mx;
    }

    public Image getImage() {
        return i;
    }
}

Can you make a small simple program (SSCCE) that shows your problem?
You've posted too much code for most people to want to work with.

He's right the longer the code the harder it is to pinpoint the problem
So for now I'll post a simple tutorial relating your problem
platform tutorial

Why you not try slick2d and use tile editor to ease your coding?

If you want help take the time to make a SSCCE and post it here.
Your whole project is too big.

Sorry about that, I think I misunderstood how to make a SSCCE properly. Although this file is still kind of big, I managed to cut about 700 kb. If I still didn't make an SSCCE properly, please let me know.

Here is the link of the file
http://www.mediafire.com/?wl3u8k6796755o9

There is no .java file in what you posted.

When I execute it, I get a continual print out of 23 for line after line????
Where and why is that printing?
The screen has a gray shaded stripped lines as image

I'm not setup to work with 6 or more files. Can you make a SSCCE that shows the problem.
Make one file with all the source in it.

Actually, that is the problem, it gets all the tiles heights, meaning the tiles do have dimensions(same thing with width, except I took out the println for that), but the tiles images can't be drawn on the screen, even though it knows where the tiles image is located.Not only that, but it uses the image for the tiles.

Here is the new version of the file you requested, with all the source in one .java file.

http://www.mediafire.com/?xbbr7ytf0e96qey

Can you explain what is happening with the code that is not what you want?
What do I have to do to see the problem?

The posted code does not execute. main() method not found.

Thanks for the reply.

In my code, the tiles images can't be drawn.
If you want to see the problem, you should look under the class level and MainConfig, where the tiles are created and drawn.

The code is in a loop that does nothing: get/load forever??????

Did you test the code that you posted?

the tiles images can't be drawn.

Please explain?

Have you tried debugging the code by adding some printlns to show what is happening as the code executes?


You have code inside of a nested loop that should be done one time out of the loop:

new ImageIcon(this.getClass().getResource("images/1.png")).getImage();

I have tried debugging the code, and adding some printlns.

In my SSCCE, map.txt has a bunch of 1s, that represents where the tiles should be. In that tile data, I have an image that is suppose to be drawn. But for some reason, it can't be drawn.

The code you posted does not execute.

Add lots more printlns to the code to show you what the code is doing.
Where are the image objects stored?
Where are they drawn?
Where does the code get the image to be drawn?

All these and more should have printlns to show what is happening.

Make the Map.txt file as small and simple as possible to shorten then number of loops that need to be done in testing. Its too big now for testing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.