Search Results

Search found 2852 results on 115 pages for '2d'.

Page 6/115 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Difficulty / Process for mobile 2D multiplayer RPG game

    - by user2827214
    I'm looking to develop a 2D multiplayer RPG game for Android, with a bird's eye view similar to that of zelda/pokemon. The game is very simple in all ways since my intent is for thousands of players to occupy the same world which I imagine requires good performance. However, I am unsure about the performance requirements of two properties: the tile map that is used as a background is dynamic (interactive). For example, a player steps in the water, and the water turns black. Every tile in the game does this. the tile map is the same object used for all players, but it is displayed differently on each user's mobile device, even though the players exist in the same world. For example, the water that turned black is displayed as red on all other players' screens. I have knowledge of java, but almost none regarding game dev. tools. Is there a best process for these requirements? Should I develop in pure java, or use some tool like Slick2D etc.? How performance intensive are these properties, if even possible? Edit: There are no collisions in the game or difficult animations, I imagining simply changing colors of the tiles like in the examples, and a client-server architecture

    Read the article

  • How to simulate pressure with particles?

    - by BeachRunnerJoe
    I'm trying to simulate pressure with a collection of spherical particles in a Unity game I'm building. A couple notes about the problem: The goal is to fill a constantly changing 2d space/void with small, frictionless spheres. The game is trying to simulate the ever-growing pressure of more objects being shoved into this space. The level itself is constantly scrolling from left to right, meaning if the space's dimensions are not changed by the user it will automatically get smaller (the leftmost part of the space will continually scroll off-screen). I'm wondering what some approaches are that I can take to tackling these problems... Knowing when to detect when there is space to fill and then add spheres to the space. Removing spheres from the space when it is shrinking. Strategies to simulate pressure on the spheres such that they "explode outwards" when more space is created. The current approach I am contemplating is using a constantly moving wall, that is off screen and moves with the screen, as this image illustrates: . This moving wall will push and trap the spheres into the space. As for adding new spheres, I was going to have either (1) spheres replicate themselves upon detecting free space, OR (2) spawn them at the left side of the space (where the wall is) - pushing the rest of the spheres to fill the space. I foresee problems with idea #1 because this likely wouldn't really create/simulate pressure; idea #2 seems more promising, but raises the question of how to provide a location for these new sphere particles to spawn (and the ramifications of spawning them when there IS no space). Thanks so much in advance for your wisdom!

    Read the article

  • Good 2D Platformer Physics

    - by Joe Wreschnig
    I have a basic character controller set up for a 2D platformer with Box2D, and I'm starting to tweak it to try to make it feel good. Physics engines have a lot of knobs to tweak, and it's not clear to me, writing with a physics engine for the first time, which ones I should use. Should jumping apply a force for several ticks? An impulse? Directly set velocity? How do I stop the avatar from sticking to walls without taking away all its friction (or do I take away all the friction, but only in the air)? Should I model the character as a capsule? A box with rounded corners? A box with two wheels? Just one big wheel? I feel like someone must have done this before! There seem to be very few resources available on the web that are not "baby's first physics", which all cut off where I'm hoping someone has already solved the issues. Most examples of physics engines for platformers have floaty-feeling controls, or in-air jumps, or easily exploitable behavior when temporary penetration is too high, etc. Some examples of what I mean: A short tap of jump jumps a short distance; a long tap jumps higher. Short skidding when stopping or reversing directions at high velocity. Standing stably on inclines (but maybe sliding down them when ducking). Analog speed when using an analog controller. All the other things that separate good platformers from bad platformers. Dare I suggest, stable moving platforms? I'm not really looking for "hey, do this." Obviously, the right thing to do is dependent on what I want in the game. But I'm hoping someone somewhere has gone through the possibilities and said "well technique A does feature X well, technique B does Y well, but that doesn't work with C", or has some worked examples beyond "if (key == space) character.impulse(0, 1)"

    Read the article

  • Collision Detection for a 2D RPG

    - by PHMitrious
    First of all, I have done some research on this topic before asking, and I'm asking this question as a mean to get some opinions on this topic, so I don't make a decision only on my own, but taking into account other people's experience as well. I'm starting a 2D online RPG project. I am using SFML for graphics and input and I'm creating a basic game structure and all for the game, creating modules for each part of the game. Well, let me get to the point I just wanted to give you guys some context. I want to decide on how I'm going to work with collision detection. Well I'm kinda going to work on maps with a tile map divided in layers (as usual) and add an extra 2 layers - not exactly in the map - for objects. So I'll have collisions between objects and agents (players - npcs - monsters - spells etc) and agents and tiles. The seconds one can be easily solved the first one need a little bit of work. I considered both creating a basic collision test engine using polygons and a quadtree to diminish tests since I'm going to be working with big maps with lots of objects - creating both a physical and graphical world representation. And I also considered using a physics engine like Box2D for collision tests. I think the first approach would take more work on my part but the second one would have the overhead of using a whole physics engine for just collision detection and no physics. What do you guys think ?

    Read the article

  • Character movement on a 2D tile map

    - by Chris Morris
    I'm working at making a HTML5 game. Top down, closest thing I can equate it to is the gameboy zeldas, but open world and no rooms. What I have so far is a procedurally generated map in a multi dimensional array. And a starting position on the map. Along with this I have an array of movable and non movable tile ID's. I also have a class for my player and have him being rendered out in the center of the starting tile. My problem however is getting the movement sorted out for the player. I want to be able to have the character free move around the map (pixel by pixel essentially) ontop of this 2D generated world. Ideally this would allow the user to move around the walk able area of the canvas. this is simple enough for me to do, but I am having problems now moving the world. If the user is 20% from the edge of the screen i want the world to start panning in the direction the player is heading. But I'm rather lacking in ideas of how to do this. I've looked around for some tutorials, but am coming up blank on ideas of how to generate the playable area (zoomed in) and to then move this generated area under the player when they reach near the end of the screen. My current idea was to generate a certain amount of tiles full size to fill the screen and place the player i the middle. Then when the user approaches the edge of the screen start generating the tiles offset by the distance moved and the direction. I can kind of see this working but I really have no idea if this is the best or easiest to code of methods for generating the world. sorry for the lack of code but I'm still just in the theory stages of working this all out.

    Read the article

  • Java : 2D Collision Detection

    - by neko
    I'm been working on 2D rectangle collision for weeks and still cannot get this problem fixed. The problem I'm having is how to adjust a player to obstacles when it collides. I'm referencing this link. The player sometime does not get adjusted to obstacles. Also, it sometimes stuck in obstacle guy after colliding. Here, the player and the obstacle are inheriting super class Sprite I can detect collision between the two rectangles and the point by ; public Point getSpriteCollision(Sprite sprite, double newX, double newY) { // set each rectangle Rectangle spriteRectA = new Rectangle( (int)getPosX(), (int)getPosY(), getWidth(), getHeight()); Rectangle spriteRectB = new Rectangle( (int)sprite.getPosX(), (int)sprite.getPosY(), sprite.getWidth(), sprite.getHeight()); // if a sprite is colliding with the other sprite if (spriteRectA.intersects(spriteRectB)){ System.out.println("Colliding"); return new Point((int)getPosX(), (int)getPosY()); } return null; } and to adjust sprites after a collision: // Update the sprite's conditions public void update() { // only the player is moving for simplicity // collision detection on x-axis (just x-axis collision detection at this moment) double newX = x + vx; // calculate the x-coordinate of sprite move Point sprite = getSpriteCollision(map.getSprite().get(1), newX, y);// collision coordinates (x,y) if (sprite == null) { // if the player is no colliding with obstacle guy x = newX; // move } else { // if collided if (vx > 0) { // if the player was moving from left to right x = (sprite.x - vx); // this works but a bit strange } else if (vx < 0) { x = (sprite.x + vx); // there's something wrong with this too } } vx=0; y+=vy; vy=0; } I think there is something wrong in update() but cannot fix it. Now I only have a collision with the player and an obstacle guy but in future, I'm planning to have more of them and making them all collide with each other. What would be a good way to do it? Thanks in advance.

    Read the article

  • Fast determination of whether objects are onscreen in 2D

    - by Ben Ezard
    So currently, I have this in each object's renderer's update method: float a = transform.position.x * Main.scale; float b = transform.position.y * Main.scale; float c = Camera.main.transform.position.x * Main.scale; float d = Camera.main.transform.position.y * Main.scale; onscreen = a + width - c > 0 && a - c < GameView.width && b + height - d > 0 && b - d < GameView.height; transform.position is a 2D vector containing the game engine's definition of where the object is - this is then multiplied by Main.scale to translate that coordinate into actual screen space Similarly, Camera.main.transform.position is the in-engine representation of where the main camera is, and this is also multiplied by Main.scale The problem is, as my game is tile-based, thousands of these updates get called every frame, just to determine whether or not each object should be drawn - how can I improve this please?

    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

  • 2D Camera Acceleration/Lag

    - by Cyral
    I have a nice camera set up for my 2D xna game. Im wondering how I should make the camera have 'acceleration' or 'lag' so it smoothly follows the player, instead of 'exactly' like mine does now. Im thinking somehow I need to Lerp the values when I set CameraPosition. Heres my code private void ScrollCamera(Viewport viewport) { float ViewMargin = .35f; float marginWidth = viewport.Width * ViewMargin; float marginLeft = cameraPosition.X + marginWidth; float marginRight = cameraPosition.X + viewport.Width - marginWidth; float TopMargin = .3f; float BottomMargin = .1f; float marginTop = cameraPosition.Y + viewport.Height * TopMargin; float marginBottom = cameraPosition.Y + viewport.Height - viewport.Height * BottomMargin; Vector2 CameraMovement; Vector2 maxCameraPosition; CameraMovement.X = 0.0f; if (Player.Position.X < marginLeft) CameraMovement.X = Player.Position.X - marginLeft; else if (Player.Position.X > marginRight) CameraMovement.X = Player.Position.X - marginRight; maxCameraPosition.X = 16 * Width - viewport.Width; cameraPosition.X = MathHelper.Clamp(cameraPosition.X + CameraMovement.X, 0.0f, maxCameraPosition.X); CameraMovement.Y = 0.0f; if (Player.Position.Y < marginTop) //above the top margin CameraMovement.Y = Player.Position.Y - marginTop; else if (Player.Position.Y > marginBottom) //below the bottom margin CameraMovement.Y = Player.Position.Y - marginBottom; maxCameraPosition.Y = 16 * Height - viewport.Height; cameraPosition.Y = MathHelper.Clamp(cameraPosition.Y + CameraMovement.Y, 0.0f, maxCameraPosition.Y); }

    Read the article

  • Fast, accurate 2d collision

    - by Neophyte
    I'm working on a 2d topdown shooter, and now need to go beyond my basic rectangle bounding box collision system. I have large levels with many different sprites, all of which are different shapes and sizes. The textures for the sprites are all square png files with transparent backgrounds, so I also need a way to only have a collision when the player walks into the coloured part of the texture, and not the transparent background. I plan to handle collision as follows: Check if any sprites are in range of the player Do a rect bounding box collision test Do an accurate collision (Where I need help) I don't mind advanced techniques, as I want to get this right with all my requirements in mind, but I'm not sure how to approach this. What techniques or even libraries to try. I know that I will probably need to create and store some kind of shape that accurately represents each sprite minus the transparent background. I've read that per pixel is slow, so given my large levels and number of objects I don't think that would be suitable. I've also looked at Box2d, but haven't been able to find much documentation, or any examples of how to get it up and running with SFML.

    Read the article

  • Implementing Camera Zoom in a 2D Engine

    - by Luke
    I'm currently trying to implement camera scaling/zoom in my 2D Engine. Normally I calculate the Sprite's drawing size and position similar to this pseudo code: render() { var x = sprite.x; var y = sprite.y; var sizeX = sprite.width * sprite.scaleX; // width of the sprite on the screen var sizeY = sprite.height * sprite.scaleY; // height of the sprite on the screen } To implement the scaling i changed the code to this: class Camera { var scaleX; var scaleY; var zoom; var finalScaleX; // = scaleX * zoom var finalScaleY; // = scaleY * zoom } render() { var x = sprite.x * Camera.finalScaleX; var y = sprite.y * Camera.finalScaleY; var sizeX = sprite.width * sprite.scaleX * Camera.finalScaleX; var sizeY = sprite.height * sprite.scaleY * Camera.finalScaleY; } The problem is that when the zoom is smaller than 1.0 all sprites are moved toward the top-left corner of the screen. This is expected when looking at the code but i want the camera to zoom on the center of the screen. Any tips on how to do that are welcome. :)

    Read the article

  • C# 2d array value check [duplicate]

    - by TLFTN
    This question already has an answer here: 3-in-a-row or more logic 4 answers I've managed to create a 2d array, then made it fill up with random numbers, like this: int[,] grid = new int[5, 5] ; Random randomNumber = new Random(); var rowLength = grid.GetLength(0); var colLength = grid.GetLength(1); for (int row = 0; row < rowLength; row++) { for (int col = 0; col < colLength; col++){ grid[row, col] = randomNumber.Next(5); Console.Write(String.Format("{0}\t", grid[row, col]));} Console.WriteLine(); } This results in an array with random values. Example: 3 0 0 3 3 1 3 3 3 2 0 0 2 0 4 3 3 2 0 3 4 0 3 3 0 Notice those three 3s which are connected to each other(in the second row), now how would I check if there's a match like this?

    Read the article

  • Using 2d collision with 3d objects

    - by Lyise
    I'm planning to write a fairly basic scrolling shoot 'em up, however, I have run into a query with regards to checking for collision. I plan to have a fixed top down view, where the player and enemies are all 3d objects on a fixed plane, and when the enemy or player fires at the other, their shots will also be along this fixed plane. In order to handle the collision, I have read up a bit on collision detection in 3d, as it is not something I have looked into previously, but I'm not sure what would be ideal for this situation. My options appear to be: Sphere collision, however, this lacks the pixel precision I would like Detection using all vertexes and planes of each object, but this seems overly convoluted for a fixed plane of play Rendering the play screen in black and white (where white is an object, black is empty space), once for enemies and once for the player, and checking for collisions that way (if a pixel is white on both, there is a collision) Which of these would be the best approach, or is there another option that I am missing? I have done this previously using 2d sprites, however I can't use the same thinking here as I don't have the image to refer to.

    Read the article

  • Provide A Scrolling "Camera" View Over A 2D Game Map

    - by BitCrash
    I'm in the process of attempting to create a 2D MMO type game with Kryonet and some basic sprites, mostly for my own learning. I have the back end set up great (By my standards) and I'm moving on to actually getting some things drawn onto the map. I cannot for the life of me figure out a solid way to have a "Camera" follow a player around a large area. The view pane for the game is 640 x 480 pixels, and each tile is 32x32 pixels (Thats 20 tiles wide and 15 high for the viewpane) I have tried a couple things to do this, but they did not seem to work out so well. I had a JScrollPane with 9 "Viewpane"-sized canvases in it, and tried to have the JScrollPane move in accordance with the player. The issue came when I reached the end of the JScrollPane. I tried to "Flip" canvases, sending the canvas currrently drawing the player to the middle of the 9 and load the corresponding maps onto the other ones. It was slow and worked poorly. I'm looking for any advice or previous experience with this; any ideas? Thank you! Edit and Clarification: I did not mean to mention Kryonet, I was merely providing peripheral information in case there was something that would help which I could not foresee. Instead of having an array of 9 canvases, why not just have one large canvas loading a large map every once in a while? I'm willing to have "load times" where as with the canvas array I would have none (in theory) to give the user a smooth experience. I could just change the size and location of the map with a modified setBounds() call on the canvas in a layered pane (layered because I have hidden swing items, like inventories and stuff) I'll try it out and post here how it goes for people asking the same question.

    Read the article

  • 2D Skeletal Animation Transformations

    - by Brad Zeis
    I have been trying to build a 2D skeletal animation system for a while, and I believe that I'm fairly close to finishing. Currently, I have the following data structures: struct Bone { Bone *parent; int child_count; Bone **children; double x, y; }; struct Vertex { double x, y; int bone_count; Bone **bones; double *weights; }; struct Mesh { int vertex_count; Vertex **vertices; Vertex **tex_coords; } Bone->x and Bone->y are the coordinates of the end point of the Bone. The starting point is given by (bone->parent->x, bone->parent->y) or (0, 0). Each entity in the game has a Mesh, and Mesh->vertices is used as the bounding area for the entity. Mesh->tex_coords are texture coordinates. In the entity's update function, the position of the Bone is used to change the coordinates of the Vertices that are bound to it. Currently what I have is: void Mesh_update(Mesh *mesh) { int i, j; double sx, sy; for (i = 0; i < vertex_count; i++) { if (mesh->vertices[i]->bone_count == 0) { continue; } sx, sy = 0; for (j = 0; j < mesh->vertices[i]->bone_count; j++) { sx += (/* ??? */) * mesh->vertices[i]->weights[j]; sy += (/* ??? */) * mesh->vertices[i]->weights[j]; } mesh->vertices[i]->x = sx; mesh->vertices[i]->y = sy; } } I think I have everything I need, I just don't know how to apply the transformations to the final mesh coordinates. What tranformations do I need here? Or is my approach just completely wrong?

    Read the article

  • 2D water with dynamic waves

    - by user1103457
    New Super Mario Bros has really cool 2D water that I'd like to learn how to create. Here's a video showing it. When something hits the water, it creates a wave. There are also constant "background" waves. You can get a good look at the constant waves just after 00:50 when the camera isn't moving. I assume the splashes in NSMB work as in the first part of this tutorial. But in NSMB the water also has constant waves on the surface, and the splashes look very different. Another difference is that in the tutorial, if you create a splash, it first creates a deep "hole" in the water at the origin of the splash. In new super mario bros this hole is absent or much smaller. I am referring to the splashes that the player creates when jumping in and out of the water. How do they create the constant waves and the splashes? I am especially interested in the splashes, and how they work together with the constant waves. I am programming in XNA. I've tried this myself, but couldn't really get it all to work well together. Bonus questions: How do they create the light spots just under the surface of the waves and how do they texture the deeper parts of the water? This is the first time I try to create water like this. EDIT: I assume the constant waves are created using a sine function. The splashes are probably created in a way like in the tutorial. (But they are not the same, so I am still interested in how to make this kind of splashes) But I have a lot of trouble combining those things. I know I can use the sine function to set the height of a specific watercolumn but the splashes are using the speed, to determine the new height. I can't figure out how to combine those. Not that I am not asking how the developers of new super mario bros did this exactly. I am just interested in ways to recreate an effect like it. This week I have an examweek so I don't have time to work on the code. After this week I will spend a lot of time on it. But I am constantly thinking about it, so that's why I will be checking comments etc. I just won't be looking at the code since it might be too time-consuming.

    Read the article

  • following a moving sprite

    - by iQue
    Im trying to get my enemies to follow my main-character of the game (2D), but for some reason the game starts lagging like crazy when I do it the way I want to do it, and the following-part dosnt work 100% either, its just 1/24 enemies that comes to my sprite, the other 23 move towards it but stay at a certain point. Might be a poor explenation but dont know how else to put it. Code for moving my enemies: private int enemyX(){ int x = 0; for (int i = 0; i < enemies.size(); i++){ if (controls.pointerPosition.x > enemies.get(i).getX()){//pointerPosition is the position of my main-sprite. x = 5; } else{ x=-5; } Log.d(TAG, "happyX HERE: " + controls.pointerPosition.x); Log.d(TAG, "enemyX HERE: " + enemies.get(i).getX()); } return x; } private int enemyY(){ int y = 0; for (int i = 0; i < enemies.size(); i++){ if (controls.pointerPosition.y > enemies.get(i).getY()){ y = 5; } else{ y=-5; } } return y; } I send it to the update-method in my Enemy-class: private void drawEnemy(Canvas canvas){ addEnemies(); // a method where I add enemies to my arrayList, no parameters except bitmap. for(int i = 0; i < enemies.size(); i++){ enemies.get(i).update(enemyX(), enemyY()); } for(int i = 0; i < enemies.size(); i++){ enemies.get(i).draw(canvas); } } and finally, the update-method itself, located in my Enemy-class: public void update(int velX, int velY) { x += velX; //sets x before I draw y += velY; //sets y before I draw currentFrame = ++currentFrame % BMP_COLUMNS; } So can any1 figure out why it starts lagging so much and how I can fix it? Thanks for your time!

    Read the article

  • Drawing 2D Grid in 3D View - Need help with method

    - by Deukalion
    I'm trying to draw a simple 2D grid for an editor, to able to navigate more clearly around the 3D space, but I can't render it: Grid2D class, creates a grid of a certain size at a location and should just draw lines. public class Grid2D : IShape { private VertexPositionColor[] _vertices; private Vector2 _size; private Vector3 _location; private int _faces; public Grid2D(Vector2 size, Vector3 location, Color color) { float x = 0, y = 0; if (size.X < 1f) { size.X = 1f; } if (size.Y < 1f) { size.Y = 1f; } _size = size; _location = location; List<VertexPositionColor> vertices = new List<VertexPositionColor>(); _faces = 0; for (y = -size.Y; y <= size.Y; y++) { vertices.Add(new VertexPositionColor(location + new Vector3(-size.X, y, 0), color)); vertices.Add(new VertexPositionColor(location + new Vector3(size.X, y, 0), color)); _faces++; } for (x = -size.X; x <= size.X; x++) { vertices.Add(new VertexPositionColor(location + new Vector3(x, -size.Y, 0), color)); vertices.Add(new VertexPositionColor(location + new Vector3(x, size.Y, 0), color)); _faces++; } _vertices = vertices.ToArray(); } public void Render(GraphicsDevice device) { device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, _vertices, 0, _faces); } } Like this: +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ Anyone knows what I'm doing wrong? If I add a Shape without texture, it's set automatically to VertexColorEnabled and TextureEnabled = false. This is how I render it: foreach (RenderObject render in _renderObjects) { render.Effect.Projection = projection; render.Effect.View = view; render.Effect.World = world; foreach (EffectPass pass in render.Effect.CurrentTechnique.Passes) { pass.Apply(); try { // Could be a Grid2D render.Shape.Render(_device); } catch { throw; } } } Exception is thrown: The current vertex shader declaration does not include all the elements required by the current Vertex Shader. Normal0 is missing. Simply put, I can't figure out how to draw a few lines. I want to draw them one at a time and I guess that's the problem I haven't figured out, and even when I tried rendering vertices[i], vertices[i+1] and primitiveCount = 1, vertices = 2, and so on it didn't work either. Any suggestions?

    Read the article

  • Java 2D Tile Collision

    - by opiop65
    I have been working on a way to do collision detection forever, and just can't figure it out. Here's my simple 2D array: for (int x = 0; x < 16; x++) { for (int y = 0; y < 16; y++) { map[x][y] = AIR; if(map[x][y] == AIR) { air.draw(x * tilesize, y * tilesize); } } } for (int x = 0; x < 16; x++) { for (int y = 6; y < 16; y++) { map[x][y] = GRASS; if(map[x][y] == GRASS) { grass.draw(x * tilesize, y * tilesize); } } } for (int x = 0; x < 16; x++) { for (int y = 8; y < 16; y++) { map[x][y] = STONE; if(map[x][y] == STONE) { stone.draw(x * tilesize, y * tilesize); } } } I want to do it with rectangles, and using the intersect() method, but how would I go about adding rectangles to all the tiles? Edit: My player moves like this: if(input.isKeyDown(Input.KEY_W)) { shiftY -= delta * speed; idY = (int) shiftY; if(shift == true) { shiftY -= delta * runspeed; } if(isColliding == true) { shiftY += delta * speed; } } if(input.isKeyDown(Input.KEY_S)) { shiftY += delta * speed; idY = (int) shiftY; if(shift == true) { shiftY += delta * runspeed; } if(isColliding == true) { shiftY -= delta * speed; } } if (input.isKeyDown(Input.KEY_A)) { steve = left; shiftX -= delta * speed; idX = (int) shiftX; if(shift == true) { shiftX -= delta * runspeed; } if(isColliding == true) { shiftX += delta * speed; } } if (input.isKeyDown(Input.KEY_D)) { steve = right; shiftX += delta * speed; idX = (int) shiftX; if(shift == true) { shiftX += delta * runspeed; } if(isColliding == true) { shiftX -= delta * speed; } } (I have tried my own collision code, but its horrible. Doesn't work in the slightest)

    Read the article

  • Best system for creating a 2d racing track

    - by tesselode
    I am working a 2D racing game and I'm trying to figure out what is the best way to define the track. At the very least, I need to be able to create a closed circuit with any amount of turns at any angle, and I need vehicles to collide with the edges of the track. I also want the following things to be true if possible (but they are optional): The code is simple and free of funky workarounds and extras I can define all of the parts of the track (such as turns) relative to the previous parts I can predict the exact position of the road at a certain point (that way I can easily and cleanly make closed circuits) Here are my options: Use a set of points. This is my current system. I have a set of turns and width changes that the track is supposed to make over time. I have a point which I transform according to these instructions, and I place a point every 5 steps or so, depending on how precise I want the track to be. These points make up the track. The main problem with this is the discrepancy between the collisions and the way the track is drawn. I won't get into too much detail, but the picture below shows what is happening (although it is exaggerated a bit). The blue lines are what is drawn, the red lines are what the vehicle collides with. I could work around this, but I'd rather avoid funky workaround code. Beizer curves. These seem cool, but my first impression of them is that they'll be a little daunting to learn and are probably too complicated for my needs. Some other kind of curve? I have heard of some other kinds of curves; maybe those are more applicable. Use Box2D or another physics engine. Instead of defining the center of the track, I could use a physics engine to define shapes that make up the road. The downside to this, however, is that I have to put in a little more work to place the checkpoints. Something completely different. Basically, what is the simplest system for generating a race track that would allow me to create closed circuits cleanly, handle collisions, and not have a ton of weird code?

    Read the article

  • 2D collision resolving

    - by Philippe Paré
    I've just worked out an AABB collision algorithm for my 2D game and I was very satisfied until I found out it only works properly with movements of 1 in X and 1 in Y... here it is: public bool Intersects(Rectanglef rectangle) { return this.Left < rectangle.Right && this.Right > rectangle.Left && this.Top < rectangle.Bottom && this.Bottom > rectangle.Top; } public bool IntersectsAny(params Rectanglef[] rectangles) { for (int i = 0; i < rectangles.Length; i++) { if (this.Left < rectangles[i].Right && this.Right > rectangles[i].Left && this.Top < rectangles[i].Bottom && this.Bottom > rectangles[i].Top) return true; } return false; } and here is how I use it in the update function of my player : public void Update(GameTime gameTime) { Rectanglef nextPosX = new Rectanglef(AABB.X, AABB.Y, AABB.Width, AABB.Height); Rectanglef nextPosY; if (Input.Key(Key.Left)) nextPosX.X--; if (Input.Key(Key.Right)) nextPosX.X++; bool xFree = !nextPosX.IntersectsAny(Boxes.ToArray()); if (xFree) nextPosY = new Rectanglef(nextPosX.X, nextPosX.Y, nextPosX.Width, nextPosX.Height); else nextPosY = new Rectanglef(AABB.X, AABB.Y, AABB.Width, AABB.Height); if (Input.Key(Key.Up)) nextPosY.Y--; if (Input.Key(Key.Down)) nextPosY.Y++; bool yFree = !nextPosY.IntersectsAny(Boxes.ToArray()); if (yFree) AABB = nextPosY; else if (xFree) AABB = nextPosX; } What I'm having trouble with, is a system where I can give float values to my movement and make it so there's a smooth acceleration. Do I have to retrieve the collision rectangle (the rectangle created by the other two colliding)? or should I do some sort of vector and go along this axis until I reach the collision? Thanks a lot!

    Read the article

  • default xna 4.0 gametime don´t works well for 2D physics

    - by EusKoder
    I am developing a game using Visual Studio 2010 and XNA 4.0, after advancing to some extent with the project (a platform based 2d platformer msdn starter kit) I got to test it on different computers with different hardware (CPU, graphics, etc.) and I found that the speed of movement object of the game is quite different, I implemented the PSK physics msdn that are based on time, /// <summary> /// Updates the player's velocity and position based on input, gravity, etc. /// </summary> public void ApplyPhysics(GameTime gameTime) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; Vector2 previousPosition = Position; // Base velocity is a combination of horizontal movement control and // acceleration downward due to gravity. velocity.X += movement * MoveAcceleration * elapsed; velocity.Y = MathHelper.Clamp(velocity.Y + GravityAcceleration * elapsed, -MaxFallSpeed, MaxFallSpeed); velocity.Y = DoJump(velocity.Y, gameTime); // Apply pseudo-drag horizontally. if (IsOnGround) velocity.X *= GroundDragFactor; else velocity.X *= GroundDragFactor; //velocity.X *= AirDragFactor; // Prevent the player from running faster than his top speed. velocity.X = MathHelper.Clamp(velocity.X, -MaxMoveSpeed, MaxMoveSpeed); // Apply velocity. Position += velocity *elapsed; Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y)); // If the player is now colliding with the level, separate them. HandleCollisions(gameTime); // If the collision stopped us from moving, reset the velocity to zero. if (Position.X == previousPosition.X) velocity.X = 0; if (Position.Y == previousPosition.Y) { velocity.Y = 0; jumpTime = 0.0f; } } tested eg with a PC (PC1) 2.13GHz Intel Core 2 6400 / ATI Radeon HD 4670 and another one: (pc2) 3.00GHz Intel Pentium D / Intel 82945G Express Chipset Family by displacement difference (moving x axis at supossed (position = velocity * gametime.ElapsedGameTime.TotalSeconds) constant velocity, for example) is 3 seconds in a total of 20 (example: moving pc1 player sprite 6000 pixels in the x-axis at 20 seconds and pc 2 runs the same distance in 17 ). Tested on a 3rd PC: i72700k / Gigabyte GTX 560 TI the results are even worse, after some time after starting the game gets like 3 times slower and showing the number of pixels in each frame moved in a debug window in the game (counting updatespersecond with counter variable for updates cuantity and gametime for counting a second show 63fps), it appears as if the number is always constant ( refreshments lose the Update method?). In this pc if I put the game in fullscreen during the course of the game, the effect of "go slow" is immediate and restore window mode sometimes yield returns to "normal" and sometimes not. Eventually I began to try a new project to test whether the movement is constant in different pc loading only one sprite and its position value in screen printing. Occur The same. I even tried moving a constant amount of pixels explicitly (position + = 5) and different speeds in different pc quantities of pixels moved in x time. I have the game loop as the default (fixedTimeStep=true;SynchronizeWithVerticalRetrace=true;). I've also tried turning off and creating another timestep as discussed in different post (eg http://gafferongames.com/game-physics/fix-your-timestep/ but i can´t achieve the desired result, move the same number of pixels in X seconds on different computers with windows. All pc used for tests use windows 7 enterprise pc1 == x86 the others are x64. The weirdest thing is that I find information about people describing the same problem and that I wear long nights of searches. Thanks for your help.

    Read the article

  • Viewport / Camera Calculation in 2D Game

    - by Dave
    we have a 2D game with some sprites and tiles and some kind of camera/viewport, that "moves" around the scene. so far so good, if we wouldn't had some special behaviour for your camera/viewport translation. normally you could stick the camera to your player figure and center it, resulting in a very cheap, undergraduate, translation equation, like : vec_translation -/+= speed (depending in what keys are pressed. WASD as default.) buuuuuuuuuut, we want our player figure be able to actually reach the bounds, when the viewport/camera has reached a maximum translation. we came up with the following solution (only keys a and d are the shown here, the rest is just adaption of calculation or maybe YOUR super-cool and elegant solution :) ): if(keys[A]) { playerX -= speed; if(playerScreenX <= width / 2 && tx < 0) { playerScreenX = width / 2; tx += speed; } else if(playerScreenX <= width / 2 && (tx) >= 0) { playerScreenX -= speed; tx = 0; if(playerScreenX < 0) playerScreenX = 0; } else if(playerScreenX >= width / 2 && (tx) < 0) { playerScreenX -= speed; } } if(keys[D]) { playerX += speed; if(playerScreenX >= width / 2 && (-tx + width) < sceneWidth) { playerScreenX = width / 2; tx -= speed; } if(playerScreenX >= width / 2 && (-tx + width) >= sceneWidth) { playerScreenX += speed; tx = -(sceneWidth - width); if(playerScreenX >= width - player.width) playerScreenX = width - player.width; } if(playerScreenX <= width / 2 && (-tx + width) < sceneWidth) { playerScreenX += speed; } } i think the code is rather self explaining: keys is a flag container for currently active keys, playerX/-Y is the position of the player according to world origin, tx/ty are the translation components vital to background / npc / item offset calculation, playerOnScreenX/-Y is the actual position of the player figure (sprite) on screen and width/height are the dimensions of the camera/viewport. this all looks quite nice and works well, but there is a very small and nasty calculation error, which in turn sums up to some visible effect. let's consider following piece of code: if(playerScreenX <= width / 2 && tx < 0) { playerScreenX = width / 2; tx += speed; } it can be translated into plain english as : if the x position of your player figure on screen is less or equal the half of your display / camera / viewport size AND there is enough space left LEFT of your viewport/camera then set players x position on screen to width half, increase translation (because we subtract the translation from something we want to move). easy, right?! doing this will create a small delta between playerX and playerScreenX. after so much talking, my question appears now here at the bottom of this document: how do I stick the calculation of my player-on-screen to the actual position of the player AND having a viewport that is not always centered aroung the players figure? here is a small test-case in processing: http://pastebin.com/bFaTauaa thank you for reading until now and thank you in advance for probably answering my question.

    Read the article

  • Collision 2D Quads

    - by Vico Pelaez
    I want to detect collision between two 2D squares, one square is static and the other one moves according to keyboard arrows. I have implemented some code, however nothing happens when they overlap each other and what I tried to achieve in the code was to detect an overlapping between them. I think I am either not understanding the concept really well or that because one of the squares is moving this is not working. Please I would really appreciate your help. Thank you! float x1=0.05 ,Y1=0.05; float x2=0.05 ,Y2=0.05; float posX1 =0.5, posY1 = 0.5; float movX2 = 0.0 , movY2 = 0.0; struct box{ int width=0.1; int heigth=0.1; }; void init(){ glClearColor(0.0, 0.0, 0.0, 0.0); glColor3f(1.0, 1.0, 1.0); } void quad1(){ glTranslatef(posX1, posY1, 0.0); glBegin(GL_POLYGON); glColor3f(0.5, 1.0, 0.5); glVertex2f(-x1, -Y1); glVertex2f(-x1, Y1); glVertex2f(x1,Y1); glVertex2f(x1,-Y1); glEnd(); } void quad2(){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glPushMatrix(); glTranslatef(movX2, movY2, 0.0); glBegin(GL_POLYGON); glColor3f(1.5, 1.0, 0.5); glVertex2f(-x2, -Y2); glVertex2f(-x2, Y2); glVertex2f(x2,Y2); glVertex2f(x2,-Y2); glEnd(); glPopMatrix(); } void reset(){ //Reset position of square??? movX2 = 0.0; movY2 = 0.0; collisionB = false; } bool collision(box A, box B){ int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; //Calculate the sides of box A leftA = x1; rightA = x1 + A.width; topA = Y1; bottomA = Y1 + A.heigth; //Calculate the sides of box B leftB = x2; rightB = x2 + B.width; topB = Y1; bottomB = Y1+ B.heigth ; if( bottomA <= topB ) return false; if( topA >= bottomB ) return false; if( rightA <= leftB ) return false; if( leftA >= rightB ) return false; return true; } float move_unit = 0.1; void keyboardown(int key, int x, int y) { switch (key){ case GLUT_KEY_UP: movY2 += move_unit; break; case GLUT_KEY_RIGHT: movX2 += move_unit; break; case GLUT_KEY_LEFT: movX2 -= move_unit; break; case GLUT_KEY_DOWN: movY2 -= move_unit; break; default: break; } glutPostRedisplay(); } void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); cuad1(); if (!collision) { cuad2(); } else{ reset(); } glFlush(); } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0, 0); glutCreateWindow("Collision Practice"); glutSpecialFunc(keyboardown); glutDisplayFunc(display); init(); glutMainLoop(); }

    Read the article

  • 2D Selective Gaussian Blur

    - by Joshua Thomas
    I am attempting to use Gaussian blur on a 2D platform game, selectively blurring specific types of platforms with different amounts. I am currently just messing around with simple test code, trying to get it to work correctly. What I need to eventually do is create three separate render targets, leave one normal, blur one slightly, and blur the last heavily, then recombine on the screen. Where I am now is I have successfully drawn into a new render target and performed the gaussian blur on it, but when I draw it back to the screen everything is purple aside from the platforms I drew to the target. This is my .fx file: #define RADIUS 7 #define KERNEL_SIZE (RADIUS * 2 + 1) //----------------------------------------------------------------------------- // Globals. //----------------------------------------------------------------------------- float weights[KERNEL_SIZE]; float2 offsets[KERNEL_SIZE]; //----------------------------------------------------------------------------- // Textures. //----------------------------------------------------------------------------- texture colorMapTexture; sampler2D colorMap = sampler_state { Texture = <colorMapTexture>; MipFilter = Linear; MinFilter = Linear; MagFilter = Linear; }; //----------------------------------------------------------------------------- // Pixel Shaders. //----------------------------------------------------------------------------- float4 PS_GaussianBlur(float2 texCoord : TEXCOORD) : COLOR0 { float4 color = float4(0.0f, 0.0f, 0.0f, 0.0f); for (int i = 0; i < KERNEL_SIZE; ++i) color += tex2D(colorMap, texCoord + offsets[i]) * weights[i]; return color; } //----------------------------------------------------------------------------- // Techniques. //----------------------------------------------------------------------------- technique GaussianBlur { pass { PixelShader = compile ps_2_0 PS_GaussianBlur(); } } This is the code I'm using for the gaussian blur: public Texture2D PerformGaussianBlur(Texture2D srcTexture, RenderTarget2D renderTarget1, RenderTarget2D renderTarget2, SpriteBatch spriteBatch) { if (effect == null) throw new InvalidOperationException("GaussianBlur.fx effect not loaded."); Texture2D outputTexture = null; Rectangle srcRect = new Rectangle(0, 0, srcTexture.Width, srcTexture.Height); Rectangle destRect1 = new Rectangle(0, 0, renderTarget1.Width, renderTarget1.Height); Rectangle destRect2 = new Rectangle(0, 0, renderTarget2.Width, renderTarget2.Height); // Perform horizontal Gaussian blur. game.GraphicsDevice.SetRenderTarget(renderTarget1); effect.CurrentTechnique = effect.Techniques["GaussianBlur"]; effect.Parameters["weights"].SetValue(kernel); effect.Parameters["colorMapTexture"].SetValue(srcTexture); effect.Parameters["offsets"].SetValue(offsetsHoriz); spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect); spriteBatch.Draw(srcTexture, destRect1, Color.White); spriteBatch.End(); // Perform vertical Gaussian blur. game.GraphicsDevice.SetRenderTarget(renderTarget2); outputTexture = (Texture2D)renderTarget1; effect.Parameters["colorMapTexture"].SetValue(outputTexture); effect.Parameters["offsets"].SetValue(offsetsVert); spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect); spriteBatch.Draw(outputTexture, destRect2, Color.White); spriteBatch.End(); // Return the Gaussian blurred texture. game.GraphicsDevice.SetRenderTarget(null); outputTexture = (Texture2D)renderTarget2; return outputTexture; } And this is the draw method affected: public void Draw(SpriteBatch spriteBatch) { device.SetRenderTarget(maxBlur); spriteBatch.Begin(); foreach (Brick brick in blueBricks) brick.Draw(spriteBatch); spriteBatch.End(); blue = gBlur.PerformGaussianBlur((Texture2D) maxBlur, helperTarget, maxBlur, spriteBatch); spriteBatch.Begin(); device.SetRenderTarget(null); foreach (Brick brick in redBricks) brick.Draw(spriteBatch); foreach (Brick brick in greenBricks) brick.Draw(spriteBatch); spriteBatch.Draw(blue, new Rectangle(0, 0, blue.Width, blue.Height), Color.White); foreach (Brick brick in purpleBricks) brick.Draw(spriteBatch); spriteBatch.End(); } I'm sorry about the massive brick of text and images(or not....new user, I tried, it said no), but I wanted to get my problem across clearly as I have been searching for an answer to this for quite a while now. As a side note, I have seen the bloom sample. Very well commented, but overly complicated since it deals in 3D; I was unable to take what I needed to learn form it. Thanks for any and all help.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >