Tile collision

Hi all,
I have a sprite climbing a ladder and it works well enough. However the ladder is part of the background and i have the sprite colliding with the back ground in order to enable the sprite to climb. ( eg :- mDiver.collidesWith(mBackground,true) )
Is it possible to have the sprite colliding with the ladder tile rather than the sprite colliding with the entire background?
Any comments or thoughts would be most welcome.
Thank you
private void createBackground(String backgroundImageName) throws IOException
          // Create the tiled layer.
          Image backgroundImage = Image.createImage(backgroundImageName);
          int[] map = {
                    0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 1, 9, 9, 9, 9, 9,
                    0, 0, 1, 0, 0, 0, 0, 0,
                    0, 0, 1, 0, 0, 0, 0, 0,
                    10, 10, 10, 10, 10, 10, 10, 10
          mBackground = new TiledLayer(8, 5, backgroundImage, 48, 48);
          // no. columns, no. rows, image, tileWidth, tileHeight
          mBackground.setPosition(12, 0);    // moved in from left
          for (int i = 0; i < map.length; i++)
               int column = i % 8;
               int row = (i - column) / 8;
               mBackground.setCell(column, row, map);
          mLayerManager.insert(mBackground, 0);
     } // end of createBackground()else if ((keyStates & UP_PRESSED) != 0)
               if(mDiver.collidesWith(mBackground,true))
                    setDirection(kRight);
                    setState(kClimbing);
                    mBackground.move(0, 3);// move scenery left
                    mClimbing = true;
                    mDiver.nextFrame();
               else
                    mClimbing = false;

Look in the API under Graphics2D:
     hit(Rectangle rect, Shape s, boolean onStroke)
          Checks whether or not the specified Shape intersects the specified Rectangle, which is in device space.

Similar Messages

  • Tile Based Collision Detection

    I am following Tonypa's Tile Based Tutorials and I have to
    say, they are great. He covers everything needed, except for one
    thing I am troubled on - Refering to Tutorial 9,
    http://www.tonypa.pri.ee/tbw/tut09.html,
    Stupid Enemy, instead of an enemy I want to make this a NPC who
    walks around in a village. So what do I do to make it so that I, or
    the char, doesn't walk right over the enemy/NPC? I am trying to
    develop an RPG, and it would look silly to have the character walk
    on top of the NPC. Can someone provided a snippet on how to make a
    collision detection with the NPC and not walk on top/under the NPC?
    One last favor to ask: What if I want to talk to the NPC if I
    am within a half tile? Would anyone be willing to share info on how
    this as well?
    Thanks a bunch in advance

    Ok, let me see if I get the read correct here: you have your scenery objects as tiles and when moving your players/NPC's through the scenery you are not scrolling the background as you go, but when you get to s certain point you want to scroll the tiles of the background also, so you can have new scenery cycle in as needed an still have the tiled background objects and new tiled background objects work for collision detection.
    If my take on your project is correct, then you have to make your tiles addressed with relative addressing formulas as you'll probably need to do with your sprites also.
    So the way this will go is that you have to make an offset and add them into your formula based on your character position. Then based on your character position you can choose to scroll your tiles left, right, up, down or what ever you choose to support. As a tile falls fully off the screen, you can dispose of it or cycle back through depending on how you implement your background.

  • URGENT: Collision Detection In Tiled Map

    HELP!!!!! I am creating a tile map of size 32*32. And the character image size is also 32*32. Now i am stuck in making collision with the walls. I have tried my own method but to no avail. Has anyone tried to doing collision detection? Need a simple logic method to detect the collision...
    (Using keyevent to control the character moving around)
    Pls I really appreciate your help!!!!!!!
    Thanks.....

    I assume you have some way of knowing that you need to display a wall tile on the map, so before you move a particular direction check to see if the square you will move to is an acceptable move (no wall, door, mountain, water etc). If it is unacceptable play a little sound or display a message, otherwise do the move.

  • 2D Pixel Collision detection on XML tiled map

    Hello,
    I'm designing a game where the player can move through a city composed of 2D image tiles. Right now we have successfully got the pixel collision detection to work on a large single image consisting of an invisible mask image and a visible image that shows a cluster of buildings and objects. The mask overlays the visible buildings and blocks / allows movement based on the color of the mask. Black is a collision, white is open space, etc.
    But this technique won't work for the game, since there will be many cities and vastly larger than this little testbed. I cannot create multiple huge cities into one file - the file would be several megs large, and I'm looking at dozens of cities.
    My idea is to create tiled maps, which will save the coordinates for the various building/object tiles in an XML file. However, I do not know how to make the collision detection work with such a tiled map. Moreover, I don't know if constructing a mosaic city using XML coordinates is the best way to go - I'm open for suggestions. My goal is to simply be able to assemble a city from individual tiles of buildings and masks, and drive/walk my character through the city with pixel collision detection, without using the current setup of a single image and a single mask.
    Any advice/suggestions offered will be GREATLY appreciated! This is our first Java project, but hopefully we can make this work.
    Thank you so much!
    Message was edited by:
    Gateway2007 - clarifying that this is a collision detection based on pixels, not planes or other method.

    Sound like this might be too late of a suggestion, but have you looked at Slick at all?
    http://slick.cokeandcode.com/static.php?page=features
    It might help with the tiling and collision aspects.

  • Collision Detection with Tiled Map

    I have a 32*32 tile map size and also 32*32 size image character. I am having difficulty in having the character avoiding walking through the wall. It keeps moving through the wall. Has anyone ever done any similar things as I am? Just need a simple logic method to detect collision with the wall. Thanks

    I usually use simple math against the coordinates of the image to the border of whatever construct is in the way.
    My character objects are usually always aware of their specific coordinate values at corners so before a MOVE, I check to see if the coordinates AFTER the move would fall outside of a specified rectangle area of allowable movement.
    If my condition checking deems it a legal move then I proceed to move the character( Image, Rectangle, etc...)

  • KeyPressed / collision detection

    I have a tile based platformer I am making and am having some trouble with the collision detection. I have it so that the game detects a collision before it actually occurs so that it wont happen in the game. However, it only appears to works right if i tap the arrow key into the wall, and if i hold the arrow key down i fly right through the tile until i let go (if i let go inside a block the hero gets stuck because it detects a collision anywhere i try to move after that). At this time i had the new coordinate to detect collision based on which direction i was moving gotten from keyPressed. Since this didnt work (assumed it was because the game loop and keyPressed dont take turns performing their actions) I made the new coordinate collision be detected from a method called in the main game loop and the result was that if I held down the key and flew into a wall, it doesnt stop exactly at the right spot (but I cant go through an entire row of tiles) but when I go the opposite direction from the collision (open space should work fine) it works fine until a point where in mid air it acts like a collision occured.
    I have tried very hard to find the error in my code concerning the collision detection and need to make sure these problems arent a result of limitations of keyPressed or something, but rather just the code i've written

    ok well I now have it set up so that before the hero moves it checks to see if the move is valid from each pixel starting at the hero to the length the hero moves in 1 directional press (using a rectangle that is the size of the hero, then has width 1 pixel larger etc until reaches the length of a move). The collision detection method returns true if there is a collision at any point, false otherwise. I tried to put the method in both the keyPressed method (for each case of a directional key pressed) as well as in the main game loop (not both at the same time) and neither worked perfectly and both worked about the same. Now the problem is that as long as the hero approaches the tile from a far away distance it works perfectly (a tile is 40 pixels in width and hero is 30), it appears that if the hero approaches from around 40 pixels out it will work but anything less and it will go through the tile as far from the 40 pixel mark it started (ie if hero starts at 37 pixels from tile and moves, it will go through the tile 3 pixels) then it can only travel back to the position it started even if there is no collision detected. Again, it appears that the hero must be about 40 pixels out (not sure if this is coincidence or it is exactly the length of the tile for a reason). Really can't figure this out, dont think there is a problem with the code i have written but probably i'm approaching the solution wrong

  • How to resolve Collision in MAS 4.0

    Hi All
    I need help on this. We are 2 developers both of us unknowigly made some changes to the same tile in 2 diffrent changlists.
    we are ready to release with lot of additional changes in the change list. It gives an collision error. We don't want to delete the change list. Is there any way we can resolve this collision.
    or at least save one of the changelist?
    Its Mobile Application Studio with CRM 4.0
    Thanks in advance
    Hetal

    Yes it is well possible to resolve the collisions in MAS. that's what called as Concurrent Development. Two users modify the same object,Collsion will result. In such cases, you need to choose which version to be released.
    Instead of writing everything here, I will provide one quick link which explains about how to resolve collisions.
    http://help.sap.com/saphelp_crm50/helpdata/en/25/96033cc68e3f05e10000000a114084/content.htm
    In your case, If you require the changes done by both the suersm then you need to go for Merge option. Please check the above link for more info.
    Best Regards
    Shankar

  • Clean Way To Prevent Signature Collision Of Mounting VHDX In Parallel PowerShell Scripting

    I have multiple Virtual Machines I am to build from a Sysprepped VHDX. (All this is done automatically via Powershell)
    For each of these Virtual Machines, I copy this VHDX and create a new one unique to the Virtual Machine. However, I wish to mount each one (in parallel) and make modifications before attaching it to the virtual machine and booting the first time. 
    The issue comes when it is time to mount the VHDX on the Physical Host, and these two processes attempt to mount at the same time. This causes a Signature Collision. I am looking for a clean - emphasis on clean - way to prevent signature collision. I have
    tried the following.
    Using the Get-Drive cmdlet and determining if one exist with a FriendlyName of "Microsoft Virtual Disk" before mounting, to detect if another VHDX is already mounted and waiting til it dismounts - the latency in this flag being available causes
    this method to fail and still the two VHDXs attempt to mount and have signature collision, breaking the script associated with that VHDX.
    I have tried using a Flag file, i.e., a text file to denote if a VHD is mounted and do a similar check - however, this relies on the file system and seems too clumsy for me. 
    I have considered Environment variables, but am afraid this is also too convoluted for such a simple task.
    Any recommendations? 

    The builds are being done in separate scripts. The purpose is that each script can be ran on it's own to rebuild a particular VM, but when the host is first built, all scripts are run concurrently to build each VM (total of 3). They could be ran sequentially,
    but the copy of the VHDX will make this take a very long time (or at least that is the thought, haven't really tested this.) The script is the same for all three builds just differentiates based on a parameter passed.
    I am currently testing the inclusion of a PauseBeforeMount parameter, which I will pass to one of the two servers in question. This way, it will only be used in the full host build, and not if a single VM is being rebuilt.
         if($PauseBeforeMount.IsPresent){ 
               Write-Host "Pausing for VHDX Mount..."
               Start-Sleep -Seconds 60 
        #Mounts the OS Disk and captures the Drive Letter 
        Write-Host "Mounting OS VHDX located at $OS_VhdPath"
        [string]$OsDriveLetter = Mount-VHD -Path $OS_VhdPath -Passthru | Get-Disk | Get-Partition | Get-Volume | `
            Where-Object {$_.FileSystemLabel -eq "OS_Disk"} | Select -ExpandProperty DriveLetter
        $OsDriveLetter += ":"
     

  • What is the best way to test for collisions between objects?

    I am in the process of developing my first game, my first decent game that is. I understand how to develop the background and tileset for the game, but have yet to figure out an effective way of testing for collisions. As in you try to move the character into a wall, or another object on the level.
    If I divide the level into tiles, it won't be to hard, but I am thinking I want to have the hero be able to move all over the place, not just from square to square.
    Any suggestions or ideas will be greatly appreciated

    If I divide the level into tiles, it won't be to hard,
    but I am thinking I want to have the hero be able to
    move all over the place, not just from square to
    square.Err...
    So if the hero is not on a square, the hero is not on a tile and consequently is not on a visible aspect of the game world?
    I suspect that you wanted the hero to be able to move in any direction, not just the standard cardinal directions.
    If you're using tiles to represent the game world, then the solution is simple - check to see if there's anything "solid" already on the target tile. If there is, abort the move and report it as a collision. If there isn't, permit the move.
    It's only when you have a tile-less world that you actually have to determine if the leading edge of your hero crosses the boundary of an item (or border) that he shouldn't be allowed to cross. Doing so is complicated enough that I would simply suggest that you search the forum for third party collision detection packages that you can borrow.

  • Collision Detections in Tilemaps

    I need some help with collision detection with tilemaps. I have the following code for the tilemap:
    import java.awt.*;
    public class TileMap {
         final int EMPTY = 0;
         final int WALL = 1;
         private static final int WIDTH = 30;
         private static final int HEIGHT = 40;
         public static final int TILE_SIZE = 15;
         private int[][] map = new int[WIDTH][HEIGHT];
         public TileMap() {
              for (int i=0;i<HEIGHT;i++) {
                   map[0] = WALL;
                   map[29][i] = WALL;     
              for (int i=0;i<WIDTH;i++) {     
                   map[i][0] = WALL;
                   map[i][39] = WALL;
         public void paint(Graphics g) {
              for (int x=0;x<WIDTH;x++) {
                   for (int y=0;y<HEIGHT;y++) {
                        if (map[x][y] == WALL) {
                             g.setColor(Color.RED);
                             g.fillRect(x*TILE_SIZE,y*TILE_SIZE,TILE_SIZE,TILE_SIZE);
    Im finding it hard to find a good tutorial on simple collision detection. Can anyone explain how i would work out some simple collision detection. For example, lets say there is one sprite, how would i figure out which tile the sprite is on? How would i detect the next sprite? Just need the concept.
    Thanks very much.
    Edited by: Java_Jenius on Jun 28, 2009 8:34 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Take a look at http://www.13thmonkey.org/~boris/jgame/ for example.
    It is an open source gaming engine and features sprites and collision detection.

  • How to collide with tile in scolling game?

    Hi all!
    I have the following problem - I want my airplane to be able to collide with a tile.
    this are the methods I'm now using but they doesn't seem to work as I want them to...
    In the GameCanvas class:
    /*method to check for collission*/
    boolean containsImpassableArea(int x, int y, int widths, int heights) {
              int rowMin = y / tHeight;
              int rowMax = (y + heights - 1) / tHeight;
              int columnMin = x / tWidth;
              int columnMax = (x + widths - 1) / tWidth;
              for (int row = rowMin; row <= rowMax; ++row) {
                   for (int column = columnMin; column <= columnMax; ++column) {
                        int cell = tBakgrund.getCell(column, row);
                        if (cell == STOP_TILE) {
                             return true;
              return false;
    /*method to check for keystates and invokes containsImpassableArea */
    private void checkKeys() throws Exception {
    int keyStates = getKeyStates();
    if ((keyStates & LEFT_PRESSED) != 0) {
                   if (sprit.getX() > 0
                             && !containsImpassableArea(sprit.getX() - 4, sprit.getY(),
                                       sprit.getWidth(), sprit.getHeight())) {
                        sprit.move(-4, 0);
                        sprit.setFrame(8);
                   } else {
                        sprit.setFrame(9);
    /*the same on RIGHT_PRESSED, UP and DOWN*/
    /* if no key is pressed */
    if ((keyStates == 0)) {
                   sprit.setFrame(9);
                   if(containsImpassableArea(sprit.getX(), sprit.getY() - 4,
                   sprit.getWidth(), sprit.getHeight())) { scrolling = false; }
                   else{
                        scrolling = true;
    /* the method that handles the scolling */
    if (terrainScroll < 0 && scrolling == true ) {
                   terrainScroll += 2;
                   tBackground.setPosition(0,terrainScroll);
    }//end of method checkkeys...
    ok.... why doesn't it work ...is it some kind of layerproblem (sprite and tiles not in the same layers)?
    Perhaps someone has any code samples?
    Thanks in advance!
    /arnold

    please use the [ code ] formatting tags when posting code.
    I'm not sure exactly, but it looks like you are only testing the end location of the player. For accurate collision detection, you need to test for collisions between all points between the start and end location. For example, if you are flying at a wall at full speed, the next calculated frame may be behind the wall, not on it. The way you implemented itI guess this is only a worry if your max speed is faster then the width or height of the sprite, but it may be something to consider once you allow variable speeds.

  • Collision Detection during Upgrade from CRM 4.0 to CRM 2007

    We are in the process of doing an upgrade from CRM 4.0 to CRM 2007. As part of this upgrade we are following the steps detailed in the mobile upgrade guide. we are currently working on the collision
    resolution issues in the mobile area. The latest issue on the UI layer is caused by changes on tiles like docactdocu2 or capsearch2 that were reverted to standard SAP.
    When solving the collisions we have been working on sub objects to these tiles. When changes to theses sub objects were finished not only the collision for the sub object was solved but no collision on the parent object was shown. But the result was that the parent objects have returned to SAP standard on vital objects like custom anchors and/or custom controllers are missing on these tiles resulting in build errors. You can easily see what happened in the version tree of these objects as no merge between the changed branch and the SAP branch took place.
    Returning to the tiles version from the changed branch is not possible though this function is offered in the version tree.
    Why is the collision resolution functionality not working as we would expect. Why can we not chsange the tile version to the changed branch.
    Has anyone else experienced these issues
    Regards
    Eddie

    Hi Shankar
    We resolved collisions on script level like "docactdocu2onLoad" by merging or accepting the change list (SAP) version. With the collision on script level being resolved the tile the script belongs to (in this case "docactdocu2") also vanished from the collision list.  The result was that the tile was reverted to the SAP version.
    With the change list being released we cannot go back to the custom version of the tile except by using the version tree. But the option "Copy to Open Version" offered by a right click on the version node wanted does not work.
    Any ideas
    Regards
    Eddie

  • What's so good about tile maps?

    I've been testing a 2d platform game I'm working on (for a bit of a laugh), and I was about to start working of some sort of tile map system for the scrolling backgrounds, and I though 'what the hey, rather than use a tile map I could just draw the whole level as one big gif', or maybe break it down to 5/8 images or something.
    Fullscreen bufferStrategy can easily handle all the unnecessary off-screen drawings and I'm not relying on image data for collisions as all collisions are done with bounding boxes (I'll eventually only be testing the onscreen bounding boxes, so there's a small saving :)
    I done a test with the player checking for 2000 (way OTT) collisions per game loop, and drawing 2 huge scrolling images (one a transparent gif the other solid, and it didn't drop a frame). Also this way there are no restrictions to the detail I can put in the background and anyone will easily be able to draw there own image and load it into the editor (when its finished) and click in a few platforms/badguys and stuff very easily.
    The background image size will probably end up about 233k per level. The screen rez will be 320/240 for that chunky pixel look.
    Am I being lazy :)

    John Carmack once described tile-based systems as, essentially, a really poor compression scheme.
    Compression aside, there is value in tile-based systems.
    You can create many, many maps (and let your users make their own) with little trouble with a map editor and a tile set. The reason Baldur's Gate, Baldur's Gate II, Icewind Dale and Icewind Dale II were so painful to make for the artists was that each map had to be hand drawn - all of it. Neverwinter Nights uses 3D tilesets, resulting in easy development, even for unskilled (in terms of art) hobbyists.

  • Putting A Layer Over Drawing Canvas - Tile Map

    I want to make it so that a layer will be above the map when its drawn.
    Like I want a layer over this, cause im making a menu for the game, but the game is above the layer.
    var tiles:Object = new Object({width:52, height:26}); // The size of the 'flat' tile. Tiles are allowed to be different dimentions, to give the '3D' effect.
    var offset:Object = new Object({x:130, y:100}); // This object helps center the 'hero' to the stage.
    var hero:Object = new Object({x:1, y:5}); // The starting position of the 'hero'
    var canvas:Object = new Object({mc:_root.createEmptyMovieClip("canvas", _root.getNextHighestDepth())}); // Contains the primary movie clip and map information.
    canvas.map = new Array( // Dictates the topography of the environment
                            // The reason I decided to to use 200 for walls and 100 for ground is to leave
                            // the option open add more tiles, such as 86 for another type of tile that is
                            // walkable. Since the collision detection code checks to see if the tile is
                            // less then 200 (less is walkable, 200 or above is not), there is no need to change
                            // the code toenable new tiles, simply name them a number between 0 and 200.
                            new Array(200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,193,196,196,196,196,189,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,194,187,182,182,179,190,100,200),
                            new Array(200,100,100,199,199,199,199,199,199,199,199,199,199,186,183,183,180,190,100,200),
                            new Array(201,199,199,199,100,100,100,100,100,100,100,100,194,186,183,183,180,190,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,194,186,183,183,180,190,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,194,186,183,183,180,190,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,194,185,181,181,178,190,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,192,195,195,195,195,188,100,200),
                            new Array(200,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,200),
                            new Array(200,100,100,100,100,100,200,200,200,200,200,200,200,200,200,200,200,200,200,200),
                            new Array(200,200,200,200,200,200,200)
    _root.onLoad = function():Void
        initmap(canvas.map); // Draw the map
        initplayer(); // Draw the player
        return;
    _root.onEnterFrame = function():Void
        input(); // Handle keyboard movement
        return;
    function input():Void // Modifies the 'hero' object, handles collision detection ('hero' and wall)
        // Any tile less then 200 is walkable, anything above is not.
        // No need to change this code handle more tiles, just name the tiles a number.
        // (not the best way to do this but simple, quick, and easy to do)
        if(Key.isDown(Key.LEFT) && canvas.map[hero.y - 1][hero.x] < 200) hero.y--;
        else if(Key.isDown(Key.RIGHT) && canvas.map[hero.y + 1][hero.x] < 200) hero.y++;
        else if(Key.isDown(Key.UP) && canvas.map[hero.y][hero.x - 1] < 200) hero.x--;
        else if(Key.isDown(Key.DOWN) && canvas.map[hero.y][hero.x + 1] < 200) hero.x++;
        move();
        return;
    function move():Void // Moves the background and the hero
        // These three lines handle swapping the tile depths to give the '3D' effect
        var d:Number = (hero.y * tiles.height) + (hero.x * tiles.width) + hero.y;
        hero.mc.swapDepths(d);
        canvas.mc["tile_" + hero.y + "_" + hero.x].swapDepths(d - 1);
        // Move the hero in the opposite direction the environment moves
        hero.mc._x = (tiles.width / 2) * (hero.y - hero.x) + offset.x;
        hero.mc._y = (tiles.height / 2) * (hero.y + hero.x) + offset.y;
        // Move the environment
        canvas.mc._x = (tiles.width / 2) * (-hero.y - -hero.x) + offset.x;
        canvas.mc._y = (tiles.height / 2) * (-hero.y + -hero.x) + offset.y;
        return;
    function initplayer():Void // Self-expalanatory
        var d:Number = (hero.y * tiles.height) + (hero.x * tiles.width) + hero.y;
        hero.mc = canvas.mc.attachMovie("hero", "hero_mc", d + 1, {_x:hero.x * tiles.width, _y:hero.y * tiles.height});
        move();
        return;
    function initmap(map:Array):Void // Render map
        var map_height:Number = map.length; // Determine height of the map
        var map_width:Number = map[0].length; // Determine width of the map
        for(var y = 0; y < map_height; y++)
            for(var x = 0; x < map_width; x++)
                // Movieclip depth is everything when doing an isometric game
                var depth:Number = (y * tiles.height) + (x * tiles.width) + y;
                // Attach tile to 'canvas'
                var tile:MovieClip = canvas.mc.attachMovie("tile" + map[y][x], "tile_" + y + "_" + x, depth);
                tile._x = (tiles.width / 2) * (y - x) + offset.x;
                tile._y = (tiles.height / 2) * (y + x) + offset.y;
        return;

    there are no layers when your fla is published (or tested).  all displayobjects are assigned depths based on code used to assign depths and compiler code that assigns depths to objects you place on-stage in the authoring environment.
    all objects placed on-stage in the authoring environment are placed at negative depths starting with about -16,380.   that's why your menu (which is probably added to some layer in the authoring environment is below the movieclip you placed at nextHighestDepth() (which adds to no depth less than zero)
    to change a movieclip's depth use the swapDepths() method of movieclips.

  • Tile Based Game Questions

    Hi, I know there are tons on posts about this topic, but I can not find the answer to my questions.
    First, how would I go about moving the world around so the char is always in the center or near center of the screen? Do I have to have some sort of offset or something?
    Second, how would I have efficient collision dection? I use the following code for movement...
    public class worldTravelPanel extends JPanel implements MouseListener
         mapGround mapGround = new mapGround();
         mapWall mapWall = new mapWall();
         mapRoof mapRoof = new mapRoof();
         mapDoor mapDoor = new mapDoor();
         mapNPC mapNPC = new mapNPC();
         Point2D start, end;
         double x, y, animationSet;
         Timer timer = new Timer();
         public worldTravelPanel()
              mapGround.loadImages("town");
              mapGround.loadTiles("olatheMap");
              mapWall.loadImages("town");
              mapWall.loadTiles("olatheMap");
              mapDoor.loadImages("town");
              mapDoor.loadTiles("olatheMap");
              mapNPC.loadImages("generic");
              mapNPC.loadTiles("olatheMap");
              mapRoof.loadImages("town");
              mapRoof.loadTiles("olatheMap");
              x = programWidth / 2;
              y = programHeight / 2;
              animationSet = 7.0;
         class moveTask extends TimerTask
              Point2D start = new Point2D.Double(hero.location[0][0], hero.location[0][1]);;
              Point2D end = new Point2D.Double(hero.location[1][0], hero.location[1][1]);
              double distance = start.distance(end);
              public void run()
                   if(((Math.abs(start.getX() - end.getX()) < 0.5) && (Math.abs(start.getY() - end.getY()) < 0.5)) && start != end)
                        start = end;
                   else if (start != end)
                        double distance = start.distance(end);
                        x = (end.getX() - start.getX()) / distance;
                        y = (end.getY() - start.getY()) / distance;
                        hero.location[1][0] = (int)(start.getX() + x);
                        hero.location[1][1] = (int)(start.getY() + y);
                        checkForCollision();
                        repaint();
                   else
                        hero.location[0][0] = (int)start.getX();
                        hero.location[0][1] = (int)start.getY();
                        timer.cancel();
              public void checkForCollision()
                   int tempX = (int)(hero.location[1][0] / 32);
                   int tempY = (int)(hero.location[1][1] / 32);
                   boolean wallCollision = false;
                        if(end.getX() > start.getX())
                        if(mapWall.currentWallMap[tempY][tempX + 1] != 00)
                             wallCollision = true;
                   else if(end.getX() < start.getX())
                        if(tempX <= 1)
                             tempX = 1;
                        if(mapWall.currentWallMap[tempY][tempX - 1] != 00)
                        wallCollision = true;
                   if(end.getY() < start.getY())
                        if(mapWall.currentWallMap[tempY + 1][tempX] != 00)
                        wallCollision = true;
                   else if(end.getY() > start.getY())
                        if(tempY <= 1)
                             tempY = 1;
                        if(mapWall.currentWallMap[tempY - 1][tempX] != 00)
                        wallCollision = true;
                   if(wallCollision == true)
                        System.out.println("Wall Collision: " + tempY + ", " + tempX);
                        //end.setLocation(hero.location[1][0], hero.location[1][1]);
                        //start.setLocation(hero.location[1][0], hero.location[1][1]);
                        start.setLocation(start.getX() + x, start.getY() + y);
                        x = start.getX();
                        y = start.getY();
                   else if(mapDoor.currentDoorMap[tempY][tempX] != 00)
                        System.out.println("Enter Door: " + mapDoor.currentDoorMap[tempY][tempX]);
                        hero.map = "olatheMap";
                        changeMap();
                   else if(mapNPC.currentNPCMap[tempY][tempX] != 00)
                        System.out.println("NPC Collision");
                        start.setLocation(start.getX() + x, start.getY() + y);
                        x = start.getX();
                        y = start.getY();
                   else
                        start.setLocation(start.getX() + x, start.getY() + y);
                        x = start.getX();
                        y = start.getY();
                   public void changeMap()
                   mapGround.loadTiles(hero.map);
                   mapWall.loadTiles(hero.map);
                   mapDoor.loadTiles(hero.map);
                   mapNPC.loadTiles(hero.map);
                   mapRoof.loadTiles(hero.map);
                   x = programWidth / 2;
                   y = programHeight / 2;
                   start.setLocation(x, y);
                   end.setLocation(x, y);
         protected void paintComponent(Graphics g)
              g.clipRect(0, 0, programWidth, programHeight);
              g.setColor(Color.white);
              g.fillRect(0, 0, programWidth, programHeight);
              mapGround.drawGround(g);//Floor Layer
              mapWall.drawWall(g);//Wall Layer
              mapDoor.drawDoor(g);//Interaction Layer 1
              mapNPC.drawNPC(g);//Interaction Layer 2
              charHero[(int)animationSet].paintIcon(this, g, (int)x, (int)y);
              mapRoof.drawRoof(g);//Roof Layer
         //Begin Mouse Listener Block
         public void mouseClicked(MouseEvent e){}
         public void mousePressed(MouseEvent e){processMouseMotion(e);}
         public void mouseReleased(MouseEvent e){}
         public void mouseEntered(MouseEvent e){}
         public void mouseExited(MouseEvent e){}
         private void processMouseMotion(MouseEvent e)
              if(e.getModifiers() == MouseEvent.BUTTON1_MASK)
                   hero.location[0][0] = (int)x;
                   hero.location[0][1] = (int)y;
                   hero.location[1][0] = (int)(e.getX() / 32) * 32 + 3;//Centers hero is tile
                   hero.location[1][1] = (int)(e.getY() / 32) * 32;//Centers hero is tile
                   timer.cancel();
                   timer = new Timer();
                   timer.schedule(new moveTask(), 0, 10);
         //End Mouse Listener Block
    }Thanks for any and all help!
    Ryltar

    I answered this here:
    http://forum.java.sun.com/thread.jsp?forum=406&thread=535480&tstart=60&trange=15
    If that doesn't work for you, ask some more specific questions and I'll try to give more help.

Maybe you are looking for