Search Results

Search found 853 results on 35 pages for 'tile'.

Page 1/35 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • A*, Tile costs and heuristic; How to approach

    - by Kevin Toet
    I'm doing exercises in tile games and AI to improve my programming. I've written a highly unoptimised pathfinder that does the trick and a simple tile class. The first problem i ran into was that the heuristic was rounded to int's which resulted in very straight paths. Resorting a Euclidian Heuristic seemed to fixed it as opposed to use the Manhattan approach. The 2nd problem I ran into was when i tried added tile costs. I was hoping to use the value's of the flags that i set on the tiles but the value's were too small to make the pathfinder consider them a huge obstacle so i increased their value's but that breaks the flags a certain way and no paths were found anymore. So my questions, before posting the code, are: What am I doing wrong that the Manhatten heuristic isnt working? What ways can I store the tile costs? I was hoping to (ab)use the enum flags for this The path finder isnt considering the chance that no path is available, how do i check this? Any code optimisations are welcome as I'd love to improve my coding. public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map ) { return FindPath( startTile, endTile, map, TileFlags.WALKABLE ); } public static List<Tile> FindPath( Tile startTile, Tile endTile, Tile[,] map, TileFlags acceptedFlags ) { List<Tile> open = new List<Tile>(); List<Tile> closed = new List<Tile>(); open.Add( startTile ); Tile tileToCheck; do { tileToCheck = open[0]; closed.Add( tileToCheck ); open.Remove( tileToCheck ); for( int i = 0; i < tileToCheck.neighbors.Count; i++ ) { Tile tile = tileToCheck.neighbors[ i ]; //has the node been processed if( !closed.Contains( tile ) && ( tile.flags & acceptedFlags ) != 0 ) { //Not in the open list? if( !open.Contains( tile ) ) { //Set G int G = 10; G += tileToCheck.G; //Set Parent tile.parentX = tileToCheck.x; tile.parentY = tileToCheck.y; tile.G = G; //tile.H = Math.Abs(endTile.x - tile.x ) + Math.Abs( endTile.y - tile.y ) * 10; //TODO omg wtf and other incredible stories tile.H = Vector2.Distance( new Vector2( tile.x, tile.y ), new Vector2(endTile.x, endTile.y) ); tile.Cost = tile.G + tile.H + (int)tile.flags; //Calculate H; Manhattan style open.Add( tile ); } //Update the cost if it is else { int G = 10;//cost of going to non-diagonal tiles G += map[ tile.parentX, tile.parentY ].G; //If this path is shorter (G cost is lower) then change //the parent cell, G cost and F cost. if ( G < tile.G ) //if G cost is less, { tile.parentX = tileToCheck.x; //change the square's parent tile.parentY = tileToCheck.y; tile.G = G;//change the G cost tile.Cost = tile.G + tile.H + (int)tile.flags; // add terrain cost } } } } //Sort costs open = open.OrderBy( o => o.Cost).ToList(); } while( tileToCheck != endTile ); closed.Reverse(); List<Tile> validRoute = new List<Tile>(); Tile currentTile = closed[ 0 ]; validRoute.Add( currentTile ); do { //Look up the parent of the current cell. currentTile = map[ currentTile.parentX, currentTile.parentY ]; currentTile.renderer.material.color = Color.green; //Add tile to list validRoute.Add( currentTile ); } while ( currentTile != startTile ); validRoute.Reverse(); return validRoute; } And my Tile class: [Flags] public enum TileFlags: int { NONE = 0, DIRT = 1, STONE = 2, WATER = 4, BUILDING = 8, //handy WALKABLE = DIRT | STONE | NONE, endofenum } public class Tile : MonoBehaviour { //Tile Properties public int x, y; public TileFlags flags = TileFlags.DIRT; public Transform cachedTransform; //A* properties public int parentX, parentY; public int G; public float Cost; public float H; public List<Tile> neighbors = new List<Tile>(); void Awake() { cachedTransform = transform; } }

    Read the article

  • Working with Tile Notifications in Windows 8 Store Apps – Part I

    - by dwahlin
    One of the features that really makes Windows 8 apps stand out from others is the tile functionality on the start screen. While icons allow a user to start an application, tiles provide a more engaging way to engage the user and draw them into an application. Examples of “live” tiles on part of my current start screen are shown next: I’ll admit that if you get enough of these tiles going the start screen can actually be a bit distracting. Fortunately, a user can easily disable a live tile by right-clicking on it or pressing and holding a tile on a touch device and then selecting Turn live tile off from the AppBar: The can also make a wide tile smaller (into a square tile) or make a square tile bigger assuming the application supports both squares and rectangles. In this post I’ll walk through how to add tile notification functionality into an application. Both XAML/C# and HTML/JavaScript apps support live tiles and I’ll show the code for both options.   Understanding Tile Templates The first thing you need to know if you want to add custom tile functionality (live tiles) into your application is that there is a collection of tile templates available out-of-the-box. Each tile template has XML associated with it that you need to load, update with your custom data, and then feed into a tile update manager. By doing that you can control what shows in your app’s tile on the Windows 8 start screen. So how do you learn more about the different tile templates and their respective XML? Fortunately, Microsoft has a nice documentation page in the Windows 8 Store SDK. Visit http://msdn.microsoft.com/en-us/library/windows/apps/hh761491.aspx to see a complete list of square and wide/rectangular tile templates that you can use. Looking through the templates you’ll It has the following XML template associated with it:  <tile> <visual> <binding template="TileSquareBlock"> <text id="1">Text Field 1</text> <text id="2">Text Field 2</text> </binding> </visual> </tile> An example of a wide/rectangular tile template is shown next:    <tile> <visual> <binding template="TileWideImageAndText01"> <image id="1" src="image1.png" alt="alt text"/> <text id="1">Text Field 1</text> </binding> </visual> </tile>   To use these tile templates (or others you find interesting), update their content, and get them to show for your app’s tile on the Windows 8 start screen you’ll need to perform the following steps: Define the tile template to use in your app Load the tile template’s XML into memory Modify the children of the <binding> tag Feed the modified tile XML into a new TileNotification instance Feed the TileNotification instance into the Update() method of the TileUpdateManager In the remainder of the post I’ll walk through each of the steps listed above to provide wide and square tile notifications for an application. The wide tile that’s shown will show an image and text while the square tile will only show text. If you’re going to provide custom tile notifications it’s recommended that you provide wide and square tiles since users can switch between the two of them directly on the start screen. Note: When working with tile notifications it’s possible to manipulate and update a tile’s XML template without having to know XML parsing techniques. This can be accomplished using some C# notification extension classes that are available. In this post I’m going to focus on working with tile notifications using an XML parser so that the focus is on the steps required to add notifications to the Windows 8 start screen rather than on external extension classes. You can access the extension classes in the Windows 8 samples gallery if you’re interested.   Steps to Create Custom App Tile Notifications   Step 1: Define the tile template to use in your app Although you can cut-and-paste a tile template’s XML directly into your C# or HTML/JavaScript Windows store app and then parse it using an XML parser, it’s easier to use the built-in TileTemplateType enumeration from the Windows.UI.Notifications namespace. It provides direct access to the XML for the various templates so once you locate a template you like in the documentation (mentioned above), simplify reference it:HTML/JavaScript var notifications = Windows.UI.Notifications; var template = notifications.TileTemplateType.tileWideImageAndText01; .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   XAML/C# var template = TileTemplateType.TileWideImageAndText01;   Step 2: Load the tile template’s XML into memory Once the target template’s XML is identified, load it into memory using the TileUpdateManager’s GetTemplateContent() method. This method parses the template XML and returns an XmlDocument object:   HTML/JavaScript   var tileXml = notifications.TileUpdateManager.getTemplateContent(template); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   XAML/C#  var tileXml = TileUpdateManager.GetTemplateContent(template);   Step 3: Modify the children of the <binding> tag Once the XML for a given template is loaded into memory you need to locate the appropriate <image> and/or <text> elements in the XML and update them with your app data. This can be done using standard XML DOM manipulation techniques. The example code below locates the image folder and loads the path to an image file located in the project into it’s inner text. The code also creates a square tile that consists of text, updates it’s <text> element, and then imports and appends it into the wide tile’s XML.   HTML/JavaScript var image = tileXml.selectSingleNode('//image[@id="1"]'); image.setAttribute('src', 'ms-appx:///images/' + imageFile); image.setAttribute('alt', 'Live Tile'); var squareTemplate = notifications.TileTemplateType.tileSquareText04; var squareTileXml = notifications.TileUpdateManager.getTemplateContent(squareTemplate); var squareTileTextAttributes = squareTileXml.selectSingleNode('//text[@id="1"]'); squareTileTextAttributes.appendChild(squareTileXml.createTextNode(content)); var node = tileXml.importNode(squareTileXml.selectSingleNode('//binding'), true); tileXml.selectSingleNode('//visual').appendChild(node); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   XAML/C#var tileXml = TileUpdateManager.GetTemplateContent(template); var text = tileXml.SelectSingleNode("//text[@id='1']"); text.AppendChild(tileXml.CreateTextNode(content)); var image = (XmlElement)tileXml.SelectSingleNode("//image[@id='1']"); image.SetAttribute("src", "ms-appx:///Assets/" + imageFile); image.SetAttribute("alt", "Live Tile"); Debug.WriteLine(image.GetXml()); var squareTemplate = TileTemplateType.TileSquareText04; var squareTileXml = TileUpdateManager.GetTemplateContent(squareTemplate); var squareTileTextAttributes = squareTileXml.SelectSingleNode("//text[@id='1']"); squareTileTextAttributes.AppendChild(squareTileXml.CreateTextNode(content)); var node = tileXml.ImportNode(squareTileXml.SelectSingleNode("//binding"), true); tileXml.SelectSingleNode("//visual").AppendChild(node);  Step 4: Feed the modified tile XML into a new TileNotification instance Now that the XML data has been updated with the desired text and images, it’s time to load the XmlDocument object into a new TileNotification instance:   HTML/JavaScript var tileNotification = new notifications.TileNotification(tileXml); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   XAML/C#var tileNotification = new TileNotification(tileXml);  Step 5: Feed the TileNotification instance into the Update() method of the TileUpdateManager Once the TileNotification instance has been created and the XmlDocument has been passed to its constructor, it needs to be passed to the Update() method of a TileUpdator in order to be shown on the Windows 8 start screen:   HTML/JavaScript notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   XAML/C#TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);    Once the tile notification is updated it’ll show up on the start screen. An example of the wide and square tiles created with the included demo code are shown next:     Download the HTML/JavaScript and XAML/C# sample application here. In the next post in this series I’ll walk through how to queue multiple tiles and clear a queue.

    Read the article

  • Java How to get exact tile location in random tile engine

    - by SYNYST3R1
    I am using the slick2d library. I want to know how to get the exact tile location so when I click on a tile it only changes that tile and not every tile on the screen. My tile generation class public Image[] tiles = new Image[3]; public int width, height; public int[][] index; public Image grass, dirt, selection; boolean selected; int mouseX, mouseY; public void init() throws SlickException { grass = new Image("assets/tiles/grass.png"); dirt = new Image("assets/tiles/dirt.png"); selection = new Image("assets/tiles/selection.png"); tiles[0] = grass; tiles[1] = dirt; width = 50; height = 50; index = new int[width][height]; Random rand = new Random(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { index[x][y] = rand.nextInt(2); } } } public void update(GameContainer gc) { Input input = gc.getInput(); mouseX = input.getMouseX(); mouseY = input.getMouseY(); if(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) { selected = true; } else{ selected = false; } } public void render() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { tiles[index[x][y]].draw(x * 64, y *64); if(IsMouseInsideTile(x, y)) selection.draw(x * 64, y * 64); } } } public boolean IsMouseInsideTile(int x, int y) { return (mouseX >= x * 64 && mouseX <= (x + 1) * 64 && mouseY >= y * 64 && mouseY <= (y + 1) * 64); } I have tried a couple different ways to change the tile I am clicking on, but I don't understand how to do it.

    Read the article

  • 2D Tile Collision free movement

    - by andrepcg
    I'm coding a 3D game for a project using OpenGL and I'm trying to do tile collision on a surface. The surface plane is split into a grid of 64x64 pixels and I can simply check if the (x,y) tile is empty or not. Besides having a grid for collision, there's still free movement inside a tile. For each entity, in the end of the update function I simply increase the position by the velocity: pos.x += v.x; pos.y += v.y; I already have a collision grid created but my collide function is not great, i'm not sure how to handle it. I can check if the collision occurs but the way I handle is terrible. int leftTile = repelBox.x / grid->cellSize; int topTile = repelBox.y / grid->cellSize; int rightTile = (repelBox.x + repelBox.w) / grid->cellSize; int bottomTile = (repelBox.y + repelBox.h) / grid->cellSize; for (int y = topTile; y <= bottomTile; ++y) { for (int x = leftTile; x <= rightTile; ++x) { if (grid->getCell(x, y) == BLOCKED){ Rect colBox = grid->getCellRectXY(x, y); Rect xAxis = Rect(pos.x - 20 / 2.0f, pos.y - 20 / 4.0f, 20, 10); Rect yAxis = Rect(pos.x - 20 / 4.0f, pos.y - 20 / 2.0f, 10, 20); if (colBox.Intersects(xAxis)) v.x *= -1; if (colBox.Intersects(yAxis)) v.y *= -1; } } } If instead of reversing the direction I set it to false then when the entity tries to get away from the wall it's still intersecting the tile and gets stuck on that position. EDIT: I've worked with Flashpunk and it has a great function for movement and collision called moveBy. Are there any simplified implementations out there so I can check them out?

    Read the article

  • Tile Collision & Sliding against tiles

    - by Devin Rawlek
    I have a tile based map with a top down camera. My sprite stops moving when he collides with a wall in any of the four directions however I am trying to get the sprite to slide along the wall if more than one directional key is pressed after being stopped. Tiles are set to 32 x 32. Here is my code; // Gets Tile Player Is Standing On var splatterTileX = (int)player.Position.X / Engine.TileWidth; var splatterTileY = (int)player.Position.Y / Engine.TileHeight; // Foreach Layer In World Splatter Map Layers foreach (var layer in WorldSplatterTileMapLayers) { // If Sprite Is Not On Any Edges if (splatterTileX < layer.Width - 1 && splatterTileX > 0 && splatterTileY < layer.Height - 1 && splatterTileY > 0) { tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West } // If Sprite Is Not On Any X Edges And Is On -Y Edge if (splatterTileX < layer.Width - 1 && splatterTileX > 0 && splatterTileY == 0) { tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West } // If Sprite Is On +X And -Y Edges if (splatterTileX == layer.Width - 1 && splatterTileY == 0) { tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West } // If Sprite Is On +X Edge And Y Is Not On Any Edge if (splatterTileX == layer.Width - 1 && splatterTileY < layer.Height - 1 && splatterTileY > 0) { tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South tileSW = layer.GetTile(splatterTileX - 1, splatterTileY + 1); // South-West tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North } // If Sprite Is On +X And +Y Edges if (splatterTileX == layer.Width - 1 && splatterTileY == layer.Height - 1) { tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North } // If Sprite Is Not On Any X Edges And Is On +Y Edge if (splatterTileX < (layer.Width - 1) && splatterTileX > 0 && splatterTileY == layer.Height - 1) { tileW = layer.GetTile(splatterTileX - 1, splatterTileY); // West tileNW = layer.GetTile(splatterTileX - 1, splatterTileY - 1); // North-West tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East } // If Sprite Is On -X And +Y Edges if (splatterTileX == 0 && splatterTileY == layer.Height - 1) { tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East } // If Sprite Is On -X Edge And Y Is Not On Any Edges if (splatterTileX == 0 && splatterTileY < (layer.Height - 1) && splatterTileY > 0) { tileN = layer.GetTile(splatterTileX, splatterTileY - 1); // North tileNE = layer.GetTile(splatterTileX + 1, splatterTileY - 1); // North-East tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South } // If Sprite Is In The Top Left Corner if (splatterTileX == 0 && splatterTileY == 0) { tileE = layer.GetTile(splatterTileX + 1, splatterTileY); // East tileSE = layer.GetTile(splatterTileX + 1, splatterTileY + 1); // South-East tileS = layer.GetTile(splatterTileX, splatterTileY + 1); // South } // Creates A New Rectangle For TileN tileN.TileRectangle = new Rectangle(splatterTileX * Engine.TileWidth, (splatterTileY - 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And N Tile var tileNCollision = player.Rectangle.Intersects(tileN.TileRectangle); // Creates A New Rectangle For TileNE tileNE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth, (splatterTileY - 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And NE Tile var tileNECollision = player.Rectangle.Intersects(tileNE.TileRectangle); // Creates A New Rectangle For TileE tileE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth, splatterTileY * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And E Tile var tileECollision = player.Rectangle.Intersects(tileE.TileRectangle); // Creates A New Rectangle For TileSE tileSE.TileRectangle = new Rectangle((splatterTileX + 1) * Engine.TileWidth, (splatterTileY + 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And SE Tile var tileSECollision = player.Rectangle.Intersects(tileSE.TileRectangle); // Creates A New Rectangle For TileS tileS.TileRectangle = new Rectangle(splatterTileX * Engine.TileWidth, (splatterTileY + 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And S Tile var tileSCollision = player.Rectangle.Intersects(tileS.TileRectangle); // Creates A New Rectangle For TileSW tileSW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth, (splatterTileY + 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And SW Tile var tileSWCollision = player.Rectangle.Intersects(tileSW.TileRectangle); // Creates A New Rectangle For TileW tileW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth, splatterTileY * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And Current Tile var tileWCollision = player.Rectangle.Intersects(tileW.TileRectangle); // Creates A New Rectangle For TileNW tileNW.TileRectangle = new Rectangle((splatterTileX - 1) * Engine.TileWidth, (splatterTileY - 1) * Engine.TileHeight, Engine.TileWidth, Engine.TileHeight); // Tile Collision Detection Between Player Rectangle And Current Tile var tileNWCollision = player.Rectangle.Intersects(tileNW.TileRectangle); // Allow Sprite To Occupy More Than One Tile if (tileNCollision && tileN.TileBlocked == false) { tileN.TileOccupied = true; } if (tileECollision && tileE.TileBlocked == false) { tileE.TileOccupied = true; } if (tileSCollision && tileS.TileBlocked == false) { tileS.TileOccupied = true; } if (tileWCollision && tileW.TileBlocked == false) { tileW.TileOccupied = true; } // Player Up if (keyState.IsKeyDown(Keys.W) || (gamePadOneState.DPad.Up == ButtonState.Pressed)) { player.CurrentAnimation = AnimationKey.Up; if (tileN.TileOccupied == false) { if (tileNWCollision && tileNW.TileBlocked || tileNCollision && tileN.TileBlocked || tileNECollision && tileNE.TileBlocked) { playerMotion.Y = 0; } else playerMotion.Y = -1; } else if (tileN.TileOccupied) { if (tileNWCollision && tileNW.TileBlocked || tileNECollision && tileNE.TileBlocked) { playerMotion.Y = 0; } else playerMotion.Y = -1; } } // Player Down if (keyState.IsKeyDown(Keys.S) || (gamePadOneState.DPad.Down == ButtonState.Pressed)) { player.CurrentAnimation = AnimationKey.Down; // Check Collision With Tiles if (tileS.TileOccupied == false) { if (tileSWCollision && tileSW.TileBlocked || tileSCollision && tileS.TileBlocked || tileSECollision && tileSE.TileBlocked) { playerMotion.Y = 0; } else playerMotion.Y = 1; } else if (tileS.TileOccupied) { if (tileSWCollision && tileSW.TileBlocked || tileSECollision && tileSE.TileBlocked) { playerMotion.Y = 0; } else playerMotion.Y = 1; } } // Player Left if (keyState.IsKeyDown(Keys.A) || (gamePadOneState.DPad.Left == ButtonState.Pressed)) { player.CurrentAnimation = AnimationKey.Left; if (tileW.TileOccupied == false) { if (tileNWCollision && tileNW.TileBlocked || tileWCollision && tileW.TileBlocked || tileSWCollision && tileSW.TileBlocked) { playerMotion.X = 0; } else playerMotion.X = -1; } else if (tileW.TileOccupied) { if (tileNWCollision && tileNW.TileBlocked || tileSWCollision && tileSW.TileBlocked) { playerMotion.X = 0; } else playerMotion.X = -1; } } // Player Right if (keyState.IsKeyDown(Keys.D) || (gamePadOneState.DPad.Right == ButtonState.Pressed)) { player.CurrentAnimation = AnimationKey.Right; if (tileE.TileOccupied == false) { if (tileNECollision && tileNE.TileBlocked || tileECollision && tileE.TileBlocked || tileSECollision && tileSE.TileBlocked) { playerMotion.X = 0; } else playerMotion.X = 1; } else if (tileE.TileOccupied) { if (tileNECollision && tileNE.TileBlocked || tileSECollision && tileSE.TileBlocked) { playerMotion.X = 0; } else playerMotion.X = 1; } } I have my tile detection setup so the 8 tiles around the sprite are the only ones detected. The collision variable is true if the sprites rectangle intersects with one of the detected tiles. The sprites origin is centered at 16, 16 on the image so whenever this point goes over to the next tile it calls the surrounding tiles. I am trying to have collision detection like in the game Secret of Mana. If I remove the diagonal checks the sprite will pass through thoses tiles because whichever tile the sprites origin is on will be the detection center. So if the sprite is near the edge of the tile and then goes up it looks like half the sprite is walking through the wall. Is there a way for the detection to occur for each tile the sprite's rectangle touches?

    Read the article

  • XNA 2D Top Down game - FOREACH didn't work for checking Enemy and Switch-Tile

    - by aldroid16
    Here is the gameplay. There is three condition. The player step on a Switch-Tile and it became false. 1) When the Enemy step on it (trapped) AND the player step on it too, the Enemy will be destroyed. 2) But when the Enemy step on it AND the player DIDN'T step on it too, the Enemy will be escaped. 3) If the Switch-Tile condition is true then nothing happened. The effect is activated when the Switch tile is false (player step on the Switch-Tile). Because there are a lot of Enemy and a lot of Switch-Tile, I have to use foreach loop. The problem is after the Enemy is ESCAPED (case 2) and step on another Switch-Tile again, nothing happened to the enemy! I didn't know what's wrong. The effect should be the same, but the Enemy pass the Switch tile like nothing happened (They should be trapped) Can someone tell me what's wrong? Here is the code : public static void switchUpdate(GameTime gameTime) { foreach (SwitchTile switch in switchTiles) { foreach (Enemy enemy in EnemyManager.Enemies) { if (switch.Active == false) { if (!enemy.Destroyed) { if (switch.IsCircleColliding(enemy.EnemyBase.WorldCenter, enemy.EnemyBase.CollisionRadius)) { enemy.EnemySpeed = 10; //reducing Enemy Speed if it enemy is step on the Tile (for about two seconds) enemy.Trapped = true; float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds; moveCounter += elapsed; if (moveCounter> minMoveTime) { //After two seconds, if the player didn't step on Switch-Tile. //The Enemy escaped and its speed back to normal enemy.EnemySpeed = 60f; enemy.Trapped = false; } } } } else if (switch.Active == true && enemy.Trapped == true && switch.IsCircleColliding(enemy.EnemyBase.WorldCenter, enemy.EnemyBase.CollisionRadius) ) { //When the Player step on Switch-Tile and //there is an enemy too on this tile which was trapped = Destroy Enemy enemy.Destroyed = true; } } } }

    Read the article

  • How to achieve selection of a tile from a tile sheet based on an ID?

    - by Bugster
    Let's say I have a tile sheet that contains 8 sprites per sheet. Each sprite is a tile of 30x30. I wrote my own custom map parser/map loader however I'm having trouble extracting a certain tile sprite from the file. I'll describe my problem better in order for everyone to understand. I wrote an enum of materials, each material has a value according to it's location relative to the tile sheet. For example void is 1, grass is 2, rock is 3, etc. So in my tile sheet they are represented as such: +---+---+---+---+---+ | 1 | 2 | 3 | 4 | 5 | +---+---+---+---+---+ Which is equivalent to: +------+-------+-------+ | void | grass | stone | +------+-------+-------+ Basically when rendering, I created a tile class, each tile has 2 coordinates: X and Y (They are calculated automatically) and a material which can be represented either as a number, either as a value (ID). When rendering, I have a vector of sprites which are all taken from 1 file called tilesheet.png, however each of them must only draw a certain portion of the tile sheet, for example say I have something like this: tile coordinateBounds(topLeftX, topLeftY, tileWidth, tileHeight); During the initialization of the map I calculate an array of tiles, and I give each of them their position, their materials based on the values in a map file and a few other variables such as collision. I need to apply the coordinateBounds to each of them according to their material value. For example if the material is grass it should only take the grass sprite from the tilesheet. I must also mention I'm using SFML, and there are no borders or spacing between the tiles.

    Read the article

  • Detecting tile with height in isometric game

    - by Carlos Navarro
    I'm trying to create an isometric tile-based game (for iPhone) and I'm having trouble with height in tiles. What I currently do (without heights) is apply some mathematic transformations to my 2D-matrix (which represent the tiles) so that I know where in the screen (x,y) should I place the isometric tile. Then, when the user clicks somewhere in the screen, I take that values and pass them through a function (kind of f^-1) to get which tile it belongs to. This works perfectly. My problem is: imagine that I want some tiles to have a different height from others. In order to draw the tile itself its pretty simple, since the z-coordinate has no transformation in the isometric approach used in games (z'=z). BUT what if I want to calculate the tile coordinate (defined by X-tile and Y-tile) from the touch coordinates (x,y)? Any guess?

    Read the article

  • Designing a flexible tile-based engine

    - by Vee
    I'm trying to create a flexible tile-based game engine to make all sorts of non-realtime puzzle games, just as Bejeweled, Civilization, Sokoban, and so on. The first approach I had was to have a 2D array of Tile objects, and then have classes inheriting from Tile that represented the game objects. Unfortunately that way I couldn't stack more game elements on the same Tile without having a 3D array. Then I did something different: I still had the 2D array of Tile objects, but every Tile object contained a List where I put and different entities. This worked fine until 20 minutes ago, when I realized that it's too expensive to do many things, look at this example: I have a Wall entity. Every update I have to check the 8 adjacent Tiles, then check all of the entities in the Tile's List, check if any of those entities is a Wall, then finally draw the correct sprite. (This is done to draw walls that are next to each other seamlessly) The only solution I see now is having a 3D array, with many layers, that could suit every situation. But that way I can't stack two entities that share the same layer on the same tile. Whenever I want to do that I have to create a new layer. Is there a better solution? What would you do?

    Read the article

  • 2D Tile Based Collision Detection

    - by MrPlosion1243
    There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same. I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in :)! I will present the code first: public void Update(GameTime gameTime) { if(Input.GetKeyDown(Keys.A)) { velocity.X -= moveAcceleration; } else if(Input.GetKeyDown(Keys.D)) { velocity.X += moveAcceleration; } if(Input.GetKeyDown(Keys.Space)) { if((onGround && isPressable) || (!onGround && airTime <= maxAirTime && isPressable)) { onGround = false; airTime += (float)gameTime.ElapsedGameTime.TotalSeconds; velocity.Y = initialJumpVelocity * (1.0f - (float)Math.Pow(airTime / maxAirTime, Math.PI)); } } else if(Input.GetKeyReleased(Keys.Space)) { isPressable = false; } if(onGround) { velocity.X *= groundDrag; velocity.Y = 0.0f; } else { velocity.X *= airDrag; velocity.Y += gravityAcceleration; } velocity.Y = MathHelper.Clamp(velocity.Y, -maxFallSpeed, maxFallSpeed); velocity.X = MathHelper.Clamp(velocity.X, -maxMoveSpeed, maxMoveSpeed); position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds; position = new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y)); if(Math.Round(velocity.X) != 0.0f) { HandleCollisions2(Direction.Horizontal); } if(Math.Round(velocity.Y) != 0.0f) { HandleCollisions2(Direction.Vertical); } } private void HandleCollisions2(Direction direction) { int topTile = (int)Math.Floor((float)Bounds.Top / Tile.PixelTileSize); int bottomTile = (int)Math.Ceiling((float)Bounds.Bottom / Tile.PixelTileSize) - 1; int leftTile = (int)Math.Floor((float)Bounds.Left / Tile.PixelTileSize); int rightTile = (int)Math.Ceiling((float)Bounds.Right / Tile.PixelTileSize) - 1; for(int x = leftTile; x <= rightTile; x++) { for(int y = topTile; y <= bottomTile; y++) { Rectangle tileBounds = new Rectangle(x * Tile.PixelTileSize, y * Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize); Vector2 depth; if(Tile.IsSolid(x, y) && Intersects(tileBounds, direction, out depth)) { if(direction == Direction.Horizontal) { position.X += depth.X; } else { onGround = true; isPressable = true; airTime = 0.0f; position.Y += depth.Y; } } } } } From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me. Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing. Thanks.

    Read the article

  • Flex Tile that expands as items are added to it

    - by Lost_in_code
    <mx:Tile width="100%" height="20"> <mx:Button label="btn"/> <mx:Button label="btn"/> <mx:Button label="btn"/> <mx:Button label="btn"/> <mx:Button label="btn"/> <mx:Button label="btn"/> </mx:Tile> The above Tile has a height of 20. When I add 50 new buttons to it, a vertical scrollbar is added. How can I make it not show the scrollbar but change it's height dynamically so that all the added items are always shown. Kinda like an "expanding" tile.

    Read the article

  • Coordinates on the top left corner or center of the tile

    - by soimon
    I'm setting up a tile system where every tile has x and y coordinates. Right now I assume that the top left corner of the tile is positioned on it's coordinate on the screen, x = tileX * tileWidth and y = tileY x tileWidth. However, it seems strange that the tile with coordinate (0, 0) is completely drawn in the 'positive' side of the coordinate system as opposed to in the center of the origin. Is it common practice to assume that a coordinate lays in the center of a tile or at the top left corner of a tile? So basically x = tileX x tileWidth or x = tileX x tilewidth - ( tileWidth / 2 )?

    Read the article

  • Pygame Tile Based Character movement speed

    - by Ryan
    Thanks for taking the time to read this. Right now I'm making a really basic tile based game. The map is a large amount of 16x16 tiles, and the character image is 16x16 as well. My character has its own class that is an extension of the sprite class, and the x and y position is saved in terms of the tile position. To note I am fairly new to pygame. My question is, I am planning to have character movement restricted to one tile at a time, and I'm not sure how to make it so that, even if the player hits the directional key dozens of time quickly, (WASD or arrow keys) it will only move from tile to tile at a certain speed. How could I implement this generally with pygame? (Similar to game movement of like Pokemon or NexusTk). Edit: I should probably note that I want it so that the player can only end a movement in a tile. He couldn't stop moving halfway inbetween a tile for example. Thanks for your time! Ryan

    Read the article

  • Java - Finding distance between player and tile in array

    - by Corey
    What is the best way performance wise to do this? When I click a tile I want it to get the distance and if I am close enough I can interact with the tile. One way would be to find the tile by doing mouse / tile width when I click correct? But then how would I get that tiles position? I know how to find the distance I just don't know how to get a certain tiles position from the array when I click it

    Read the article

  • 2D isometric: screen to tile coordinates

    - by Dr_Asik
    I'm writing an isometric 2D game and I'm having difficulty figuring precisely on which tile the cursor is. Here's a drawing: where xs and ys are screen coordinates (pixels), xt and yt are tile coordinates, W and H are tile width and tile height in pixels, respectively. My notation for coordinates is (y, x) which may be confusing, sorry about that. The best I could figure out so far is this: int xtemp = xs / (W / 2); int ytemp = ys / (H / 2); int xt = (xs - ys) / 2; int yt = ytemp + xt; This seems almost correct but is giving me a very imprecise result, making it hard to select certain tiles, or sometimes it selects a tile next to the one I'm trying to click on. I don't understand why and I'd like if someone could help me understand the logic behind this. Thanks!

    Read the article

  • Creating a XAML Tile Control

    - by psheriff
    One of the navigation mechanisms used in Windows 8 and Windows Phone is a Tile. A tile is a large rectangle that can have words and pictures that a user can click on. You can build your own version of a Tile in your WPF or Silverlight applications using a User Control. With just a little bit of XAML and a little bit of code-behind you can create a navigation system like that shown in Figure 1. Figure 1: Use a Tile for navigation. You can build a Tile User Control with just a little bit of XAML and...(read more)

    Read the article

  • Dock tile plug-ins for not running applications

    - by kiamlaluno
    Is the dock tile plug-in of an application used even when the application is not active? The documentation says that the dock title plug-in is used when the application is loaded in the dock, but that means that the application is running of that the application is put in the dock because the user wants it to stay on the dock?

    Read the article

  • AS3 - Tile image/movieclip along a line

    - by Mim Hufford
    If possible I would like to tile an image or MovieClip along a line using the standard moveTo() and lineTo() methods, The lines are directional so need to show something similar to >>>>>>>>>>>>>. The lines can be at any angle, so using drawRect() with beginBitmapFill() isn't an option. Also if possible I would like to have the lines animated. Is this possible or will it require a custom class?

    Read the article

  • 2D XNA Tile Based Lighting. Ideas and Methods

    - by Twitchy
    I am currently working on developing a 2D tile based game, similar to the game 'Terraria'. We have the base tile and chunk engine working and are now looking to implement lighting. Instead of the tile based lighting that terraria uses, I want to implement point lights for torches, etc. I have seen Catalin Zima’s shader based shadows, and this would be perfect for the torches (point lights). My problem here is that the tiles on the surface of the world need to be illuminated, doing this by a big point light is firstly extremely expensive, but also doesn't look right. What I need help with (overall) is... To have a surface that is illuminated regardless of torches, etc. To also have point lights, or smooth tile lighting similar to Catalin Zima’s shader based shadows. Looking forward to your replies. Any ideas are appreciated.

    Read the article

  • Vertical Scrolling In Tile Based XNA Platformer

    - by alec100_94
    I'm making a 2D platformer in XNA 4.0. I have created a working tile engine, which works well for my purposes, and Horizontal Scrolling works flawlessly, however I am having great trouble with Vertical scrolling. I Basically want the camera to scroll up (world to scroll down) when the player reaches a certain Y co-ordinate, and I would also like to automatically scroll back down if coming down, and that co-ordinate is passed. My biggest problem is I have no real way of detecting the direction the player is moving in using only the Y Co-ord. Here Is My Code Code For The Camera Class (which appears to be a very different approach to most camera classes I have seen). using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Marvin { class Camera : TileEngine { public static bool startReached; public static bool endReached; public static void MoveRight(float speed = 2) { //Moves The Position of Each Tile Right foreach (Tile t in tiles) { if(t!=null) { t.position.X -= speed; } } } public static void MoveLeft(float speed = 2) { //Moves The Position of Each Tile Right foreach (Tile t in tiles) { if(t!=null) { t.position.X += speed; } } } public static void MoveUp(float speed = 2) { foreach (Tile t in tiles) { if(t!=null) { t.position.Y += speed; } } } public static void MoveDown(float speed = 2) { foreach (Tile t in tiles) { if(t!=null) { t.position.Y -= speed; } } } public static void Restrain() { if(tiles.Last().position.X<Main.graphics.PreferredBackBufferWidth-tiles.Last().size.X) { MoveLeft(); endReached = true; } else { endReached = false; } if(tiles[1].position.X>0) { MoveRight(); startReached = true;} else { startReached = false; } } } } Here is My Player Code for Left and Right Scrolling/Moving if (Main.currentKeyState.IsKeyDown(Keys.Right)) { Camera.MoveRight(); if(Camera.endReached) { MoveRight(2); } else { if(marvin.GetRectangle().X!=Main.graphics.PreferredBackBufferWidth-(marvin.GetRectangle().X+marvin.GetRectangle().Width)) { MoveRight(2); Camera.MoveLeft(); } } } if(Main.currentKeyState.IsKeyDown(Keys.Left)) { Camera.MoveLeft(); if(Camera.startReached) { MoveLeft(2); } else { if(marvin.GetRectangle().X!=Main.graphics.PreferredBackBufferWidth-(marvin.GetRectangle().X+marvin.GetRectangle().Width)) { MoveLeft(2); Camera.MoveRight(); } } } Camera.Restrain(); if(marvin.GetRectangle().X>Main.graphics.PreferredBackBufferWidth-marvin.GetRectangle().Width) { MoveLeft(2); } if(marvin.GetRectangle().X<0) { MoveRight(2); } And Here Is My Player Jumping/Falling Code which may cause some conflicts with the vertical camera movement. if (!jumping) { if(!TileEngine.TopOfTileCollidingWith(footBounds)) { MoveDown(5); } else { if(marvin.GetRectangle().Y != TileEngine.LastPlatformStoodOnTop()-marvin.GetRectangle().Height) { float difference = (TileEngine.LastPlatformStoodOnTop()-marvin.GetRectangle().Height) - (marvin.GetRectangle().Y); marvin.SetRectangle(marvin.GetRectangle().X,(int)(marvin.GetRectangle().Y+difference)); armR.SetRectangle(armR.GetRectangle().X,(int)(armR.GetRectangle().Y+difference)); armL.SetRectangle(armL.GetRectangle().X,(int)(armL.GetRectangle().Y+difference)); eyeL.SetRectangle(eyeL.GetRectangle().X,(int)(eyeL.GetRectangle().Y+difference)); eyeR.SetRectangle(eyeR.GetRectangle().X,(int)(eyeR.GetRectangle().Y+difference)); } } } if (Main.currentKeyState.IsKeyDown(Keys.Up) && Main.previousKeyState.IsKeyUp(Keys.Up) && TileEngine.TopOfTileCollidingWith(footBounds)) { jumping = true; } if(jumping) { if(TileEngine.LastPlatformStoodOnTop()>0 && (TileEngine.LastPlatformStoodOnTop() - footBounds.Bottom)<120) { MoveUp(5); } else { jumping = false; } } All player code I have tried for vertical movements has failed, or caused weird results (like falling through platforms), and most have been a variation on the method I described above, hence I have not included it. I would really appreciate some help implementing a simple vertical scrolling into this game, Thanks.

    Read the article

  • How to tile multiple procedurally generated textures?

    - by Burhuc
    I'm trying to develop a procedural tile generator for a game, mostly for the ground tiles, instead of using "hand-drawn" tiles. To achieve this I'm using Perlin noise and a sine wave with multiple parameters, which already gives me pretty nice results. I don't want to generate 1 tile and repeat that one forever for one ground type, but I want to avoid recurrences, so I'm generating n different tiles. The problem I'm having now is that I want to tile the generated textures (smooth transitions). At the moment I have this: 4 256x256 textures. I thought a simple method would be to just add the positions of the different tiles to the noise generation algorithm, so that, when creating the 4 256x256 textures, it would behave like it would create a 512x512 texture, but that somehow didn't work as intented. So how can I tile those textures?

    Read the article

  • 2D Smooth Turning in a Tile-Based Game

    - by ApoorvaJ
    I am working on a 2D top-view grid-based game. A ball that rolls on the grid made up of different tiles. The tiles interact with the ball in a variety of ways. I am having difficulty cleanly implementing the turning tile. The image below represents a single tile in the grid, which turns the ball by a right angle. If the ball rolls in from the bottom, it smoothly changes direction and rolls to the right. If it rolls in from the right, it is turned smoothly to the bottom. If the ball rolls in from top or left, its trajectory remains unchanged by the tile. The tile shouldn't change the magnitude of the velocity of the ball - only change its direction. The ball has Velocity and Position vectors, and the tile has Position and Dimension vectors. I have already implemented this, but the code is messy and buggy. What is an elegant way to achieve this, preferably by modification of the ball's Velocity vector by a formula?

    Read the article

  • Finding out which tile a mouse click landed in

    - by Shard
    I am working on an icometric grid based game and im having an issue trying to link a mouse click from the user to a tile. I have been able to split the problem into 2 parts which is first finding a rectangle that sourounds a tile, which I have been able to do but the second part of figuring out from the rectangle which tile the click landed in has got me stumped. Here is an example of a rectangle with tiles on the inside: The rectangle is 70px long and 30px high so if i use an input of say 30x(top)/20y(left) how would I go about determining which tile this fell into?

    Read the article

  • problem with a very simple tile based game

    - by newbieguy
    Hello, I am trying to create a pacman-like game. I have an array that looks like this: array: 1111111111111 1000000000001 1111110111111 1000000000001 1111111111111 1 = Wall, 0 = Empty space I use this array to draw tiles that are 16x16 in size. The Game character is 32x32. Initially I represented the character's position in array indexes, [1,1] etc. I would update his position if array[character.new_y][charater.new_x] == 0 Then I translated these array coordinates to pixels, [y*16, x*16] to draw him. He was lining up nicely, wouldn't go into walls, but I noticed that since I was updating him by 16 pixels each, he was moving very fast. I decided to do it in reverse, to store the game character's position in pixels instead, so that he could use less than 16 pixels per move. I thought that a simple if statement such as this: if array[(character.new_pixel_y)/16][(character.new_pixel_x)/16] == 0 would prevent him from going into walls, but unfortunately he eats a bit of the bottom and right side walls. Any ideas how would I properly translate pixel position to the array indexes? I guess this is something simple, but I really can't figure it out :(

    Read the article

  • How to implement a multi-part snake with smooth movement? [closed]

    - by Jamie
    Sorry that i couldnt answer on my previous post but it got closed. I couldnt answer because i had to prepair for my finals. As there were problems with understanding of what im trying to achieve, im going to describe a little bit more in depth. Im creating a game in which you steer a snake. I assume everybody knows how that works. But in my case the snake isnt just propagating in an array element by element. Imagine a 2Dgrid on which the snake moves. Its 10x10 tiles. Lets say one tile is 4x4 meters. The snakes head spawns in the middle of the (3,2) tile (beginning with (0,0)), so its position is (4*3+2,4*2+2)(the 2's are so that the snake is in the middle of the 4x4 tile). And heres where the fun begins. when the snake moves, it doesnt jump to next tile. Instead it moves a fraction of the way there. So lets say the snake is heading to tile (4,2). After it moved once, its position is (4*3+2+0.1,4*2+2), where 0.1 is the fraction of the way it moved. This is done to achieve smooth movement. So now im adding the rest of the body. The rest is supposed to move along the exact same path as the head did. I implemented it so that each part of the body has its own position and direction. Then i apply this algorithm: 1.Move each part in its direction. 2.If a part is in the middle of the tile(which implies all of them are), change each parts direction to the direction of the part proceeding it. As i said before i could make this work, but i cant stop thinking that im overlooking a much easier and cleaner solution. So this is my question. Is there any easier/better/faster way to do this?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >