Search Results

Search found 3566 results on 143 pages for '2d physics'.

Page 12/143 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • 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 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

  • Point inside Oriented Bounding Box?

    - by Milo
    I have an OBB2D class based on SAT. This is my point in OBB method: public boolean pointInside(float x, float y) { float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) * (x - center.x)); float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) * (y - center.y)); return (newy > center.y - (getHeight() / 2)) && (newy < center.y + (getHeight() / 2)) && (newx > center.x - (getWidth() / 2)) && (newx < center.x + (getWidth() / 2)); } public boolean pointInside(Vector2D v) { return pointInside(v.x,v.y); } Here is the rest of the class; the parts that pertain: public class OBB2D { private Vector2D projVec = new Vector2D(); private static Vector2D projAVec = new Vector2D(); private static Vector2D projBVec = new Vector2D(); private static Vector2D tempNormal = new Vector2D(); private Vector2D deltaVec = new Vector2D(); private ArrayList<Vector2D> collisionPoints = new ArrayList<Vector2D>(); // Corners of the box, where 0 is the lower left. private Vector2D corner[] = new Vector2D[4]; private Vector2D center = new Vector2D(); private Vector2D extents = new Vector2D(); private RectF boundingRect = new RectF(); private float angle; //Two edges of the box extended away from corner[0]. private Vector2D axis[] = new Vector2D[2]; private double origin[] = new double[2]; public OBB2D(float centerx, float centery, float w, float h, float angle) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(centerx,centery,w,h,angle); } public OBB2D(float left, float top, float width, float height) { for(int i = 0; i < corner.length; ++i) { corner[i] = new Vector2D(); } for(int i = 0; i < axis.length; ++i) { axis[i] = new Vector2D(); } set(left + (width / 2), top + (height / 2),width,height,0.0f); } public void set(float centerx,float centery,float w, float h,float angle) { float vxx = (float)Math.cos(angle); float vxy = (float)Math.sin(angle); float vyx = (float)-Math.sin(angle); float vyy = (float)Math.cos(angle); vxx *= w / 2; vxy *= (w / 2); vyx *= (h / 2); vyy *= (h / 2); corner[0].x = centerx - vxx - vyx; corner[0].y = centery - vxy - vyy; corner[1].x = centerx + vxx - vyx; corner[1].y = centery + vxy - vyy; corner[2].x = centerx + vxx + vyx; corner[2].y = centery + vxy + vyy; corner[3].x = centerx - vxx + vyx; corner[3].y = centery - vxy + vyy; this.center.x = centerx; this.center.y = centery; this.angle = angle; computeAxes(); extents.x = w / 2; extents.y = h / 2; computeBoundingRect(); } //Updates the axes after the corners move. Assumes the //corners actually form a rectangle. private void computeAxes() { axis[0].x = corner[1].x - corner[0].x; axis[0].y = corner[1].y - corner[0].y; axis[1].x = corner[3].x - corner[0].x; axis[1].y = corner[3].y - corner[0].y; // Make the length of each axis 1/edge length so we know any // dot product must be less than 1 to fall within the edge. for (int a = 0; a < axis.length; ++a) { float l = axis[a].length(); float ll = l * l; axis[a].x = axis[a].x / ll; axis[a].y = axis[a].y / ll; origin[a] = corner[0].dot(axis[a]); } } public void computeBoundingRect() { boundingRect.left = JMath.min(JMath.min(corner[0].x, corner[3].x), JMath.min(corner[1].x, corner[2].x)); boundingRect.top = JMath.min(JMath.min(corner[0].y, corner[1].y),JMath.min(corner[2].y, corner[3].y)); boundingRect.right = JMath.max(JMath.max(corner[1].x, corner[2].x), JMath.max(corner[0].x, corner[3].x)); boundingRect.bottom = JMath.max(JMath.max(corner[2].y, corner[3].y),JMath.max(corner[0].y, corner[1].y)); } public void set(RectF rect) { set(rect.centerX(),rect.centerY(),rect.width(),rect.height(),0.0f); } // Returns true if other overlaps one dimension of this. private boolean overlaps1Way(OBB2D other) { for (int a = 0; a < axis.length; ++a) { double t = other.corner[0].dot(axis[a]); // Find the extent of box 2 on axis a double tMin = t; double tMax = t; for (int c = 1; c < corner.length; ++c) { t = other.corner[c].dot(axis[a]); if (t < tMin) { tMin = t; } else if (t > tMax) { tMax = t; } } // We have to subtract off the origin // See if [tMin, tMax] intersects [0, 1] if ((tMin > 1 + origin[a]) || (tMax < origin[a])) { // There was no intersection along this dimension; // the boxes cannot possibly overlap. return false; } } // There was no dimension along which there is no intersection. // Therefore the boxes overlap. return true; } public void moveTo(float centerx, float centery) { float cx,cy; cx = center.x; cy = center.y; deltaVec.x = centerx - cx; deltaVec.y = centery - cy; for (int c = 0; c < 4; ++c) { corner[c].x += deltaVec.x; corner[c].y += deltaVec.y; } boundingRect.left += deltaVec.x; boundingRect.top += deltaVec.y; boundingRect.right += deltaVec.x; boundingRect.bottom += deltaVec.y; this.center.x = centerx; this.center.y = centery; computeAxes(); } // Returns true if the intersection of the boxes is non-empty. public boolean overlaps(OBB2D other) { if(right() < other.left()) { return false; } if(bottom() < other.top()) { return false; } if(left() > other.right()) { return false; } if(top() > other.bottom()) { return false; } if(other.getAngle() == 0.0f && getAngle() == 0.0f) { return true; } return overlaps1Way(other) && other.overlaps1Way(this); } public Vector2D getCenter() { return center; } public float getWidth() { return extents.x * 2; } public float getHeight() { return extents.y * 2; } public void setAngle(float angle) { set(center.x,center.y,getWidth(),getHeight(),angle); } public float getAngle() { return angle; } public void setSize(float w,float h) { set(center.x,center.y,w,h,angle); } public float left() { return boundingRect.left; } public float right() { return boundingRect.right; } public float bottom() { return boundingRect.bottom; } public float top() { return boundingRect.top; } public RectF getBoundingRect() { return boundingRect; } public boolean overlaps(float left, float top, float right, float bottom) { if(right() < left) { return false; } if(bottom() < top) { return false; } if(left() > right) { return false; } if(top() > bottom) { return false; } return true; } public static float distance(float ax, float ay,float bx, float by) { if (ax < bx) return bx - ay; else return ax - by; } public Vector2D project(float ax, float ay) { projVec.x = Float.MAX_VALUE; projVec.y = Float.MIN_VALUE; for (int i = 0; i < corner.length; ++i) { float dot = Vector2D.dot(corner[i].x,corner[i].y,ax,ay); projVec.x = JMath.min(dot, projVec.x); projVec.y = JMath.max(dot, projVec.y); } return projVec; } public Vector2D getCorner(int c) { return corner[c]; } public int getNumCorners() { return corner.length; } public boolean pointInside(float x, float y) { float newy = (float) (Math.sin(angle) * (y - center.y) + Math.cos(angle) * (x - center.x)); float newx = (float) (Math.cos(angle) * (x - center.x) - Math.sin(angle) * (y - center.y)); return (newy > center.y - (getHeight() / 2)) && (newy < center.y + (getHeight() / 2)) && (newx > center.x - (getWidth() / 2)) && (newx < center.x + (getWidth() / 2)); } public boolean pointInside(Vector2D v) { return pointInside(v.x,v.y); } public ArrayList<Vector2D> getCollsionPoints(OBB2D b) { collisionPoints.clear(); for(int i = 0; i < corner.length; ++i) { if(b.pointInside(corner[i])) { collisionPoints.add(corner[i]); } } for(int i = 0; i < b.corner.length; ++i) { if(pointInside(b.corner[i])) { collisionPoints.add(b.corner[i]); } } return collisionPoints; } }; What could be wrong? When I getCollisionPoints for 2 OBBs I know are penetrating, it returns no points. Thanks

    Read the article

  • Perpendicularity of a normal and a velocity?

    - by Milo
    I'm trying to fake angular velocity on my vehicle when it hits a wall by getting the dot product of the normal of the edge the car is hitting and the vehicle's velocity: Vector2D normVel = new Vector2D(); normVel.equals(vehicle.getVelocity()); normVel.normalize(); float dot = normVel.dot(outNorm); dot = -dot; vehicle.setAngularVelocity(vehicle.getAngularVelocity() + (dot * vehicle.getVelocity().length() * 0.01f)); outNorm is the normal of the wall. The problem is it only works half the time. It seems no matter what, the car always goes clockwise. If the car should head clockwise: -------------------------------------- / / I want the angular velocity to be positive, otherwise if it needs to go CCW: -------------------------------------- \ \ Then the angular velocity should be negative... What should I change to achieve this? Thanks Hmmm... Im not sure why this is not working... for(int i = 0; i < buildings.size(); ++i) { e = buildings.get(i); ArrayList<Vector2D> colPts = vehicle.getRect().getCollsionPoints(e.getRect()); float dist = OBB2D.collisionResponse(vehicle.getRect(), e.getRect(), outNorm); for(int u = 0; u < colPts.size(); ++u) { Vector2D p = colPts.get(u).subtract(vehicle.getRect().getCenter()); vehicle.setTorque(vehicle.getTorque() + p.cross(outNorm)); }

    Read the article

  • Box2D Platform body not moving player body along with it

    - by onedayitwillmake
    I am creating a game using Box2D (Javascript implementation) - and I added the ability to have a static platform, that is moved along an axis as a function of a sine. My problem is when the player lands on the platform, as the platform moves along the X axis - the player is not moved along with it, as you visually would expect. The player can land on the object, and if it hits the side of the object, it does colide with it and is pushed. This image might explain better than I did: After jumping on to the red platform the player character will fall off as the platform moves to the right UPDATE: Here is a live demo showing the problem: http://onedayitwillmake.com/ChuClone/slideexample.php

    Read the article

  • 2D Side scroller collision detection

    - by Shanon Simmonds
    I am trying to do some collision detection between objects and tiles, but the tiles do not have there own x and y position, they are just rendered to the x and y position given, there is an array of integers which has the ids of the tiles to use(which are given from an image and all the different colors are assigned different tiles) int x0 = camera.x / 16; int y0 = camera.y / 16; int x1 = (camera.x + screen.width) / 16; int y1 = (camera.y + screen.height) / 16; for(int y = y0; y < y1; y++) { if(y < 0 || y >= height) continue; // height is the height of the level for(int x = x0; x < x1; x++) { if(x < 0 || x >= width) continue; // width is the width of the level getTile(x, y).render(screen, x * 16, y * 16); } } I tried using the levels getTile method to see if the tile that the object was going to advance to, to see if it was a certain tile, but, it seems to only work in some directions. Any ideas on what I'm doing wrong and fixes would be greatly appreciated. What's wrong is that it doesn't collide properly in every direction and also this is how I tested for a collision in the objects class if(!level.getTile((x + xa) / 16, (y + ya) / 16).isSolid()) { x += xa; y += ya; } EDIT: xa and ya represent the direction as well as the movement, if xa is negative it means the object is moving left, if its positive it is moving right, and same with ya except negative for up, positive for down.

    Read the article

  • Can these game be fully coded in html5/javascript?

    - by RufioLJ
    I mean the mechanics of the game. Would it be possible? -Pokemon GBA series, rendering the world would be easy, but what about battle mechanics? -MapleStory, after seen dragonbound.net which is an identical copy of Gunbound I would think it's rather possible, but I'm still not sure if javascript can handle all the mechanics of the world. It would be heavy on resources I guess? I'm asking this because I'm really interested in html5 game develop(I really think in a future will destroy flash on game dev ground). I want to have an idea of how far games developed with the html5/javascript technology can go. I got especially inspired by dragonbound. I really think it pushes htmlt/javascript to the limits (game dev).

    Read the article

  • 2D Collision in Canvas - Balls Overlapping When Velocity is High

    - by kushsolitary
    I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls. I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it: //Check collision between two bodies function collides(b1, b2) { //Find the distance between their mid-points var dx = b1.x - b2.x, dy = b1.y - b2.y, dist = Math.round(Math.sqrt(dx*dx + dy*dy)); //Check if it is a collision if(dist <= (b1.r + b2.r)) { //Calculate the angles var angle = Math.atan2(dy, dx), sin = Math.sin(angle), cos = Math.cos(angle); //Calculate the old velocity components var v1x = b1.vx * cos, v2x = b2.vx * cos, v1y = b1.vy * sin, v2y = b2.vy * sin; //Calculate the new velocity components var vel1x = ((b1.m - b2.m) / (b1.m + b2.m)) * v1x + (2 * b2.m / (b1.m + b2.m)) * v2x, vel2x = (2 * b1.m / (b1.m + b2.m)) * v1x + ((b2.m - b1.m) / (b2.m + b1.m)) * v2x, vel1y = v1y, vel2y = v2y; //Set the new velocities b1.vx = vel1x; b2.vx = vel2x; b1.vy = vel1y; b2.vy = vel2y; } } You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters: function Ball() { //Random Positions this.x = 50 + Math.random() * W; this.y = 50 + Math.random() * H; //Random radii this.r = 15 + Math.random() * 30; this.m = this.r; //Random velocity components this.vx = 1 + Math.random() * 4; this.vy = 1 + Math.random() * 4; //Random shade of grey color this.c = Math.round(Math.random() * 200); this.draw = function() { ctx.beginPath(); ctx.fillStyle = "rgb(" + this.c + ", " + this.c + ", " + this.c + ")"; ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); ctx.fill(); ctx.closePath(); } }

    Read the article

  • Basic collision direction detection on 2d objects

    - by Osso Buko
    I am trying to develop a platform game for Android by using ANdroid GL Engine (ANGLE). And I am having trouble with collision detection. I have two objects which is shaped as rectangular. And no change in rotation. Here is a scheme of attributes of objects. What i am trying to do is when objects collide they block each other's movement on that direction. Every object has 4 boolean (bTop, bBottom, bRight, bLeft). For example when bBottom is true object can't advance on that direction. I came up with a solution but it seems it only works on one dimensional. Bottom and top or right and left. public void collisionPlatform (MyObject a, MyObject b) { // first obj is player and second is a wall or a platform Vector p1 = a.mPosition; // p1 = middle point of first object Vector d1 = a.mPosition2; // width(mX) and height of first object Vector mSpeed1 = a.mSpeed; // speed vector of first object Vector p2 = b.mPosition; // p1 = middle point of second object Vector d2 = b.mPosition2; // width(mX) and height of second object Vector mSpeed2 = b.mSpeed; // speed vector of second object float xDist, yDist; // distant between middle of two object float width , height; // this is average of two objects measurements width=(width1+width2)/2 xDist=(p1.mX - p2.mX); // calculate distance // if positive first object is at the right yDist=(p1.mY - p2.mY); // if positive first object is below width = d1.mX + d2.mX; // average measurements calculate height = d1.mY + d2.mY; width/=2; height/=2; if (Math.abs(xDist) < width && Math.abs(yDist) < height) { // Two object is collided if(p1.mY>p2.mY) { // first object is below second one a.bTop = true; if(a.mSpeed.mY<0) a.mSpeed.mY=0; b.bBottom = true; if(b.mSpeed.mY>0) b.mSpeed.mY=0; } else { a.bBottom = true; if(a.mSpeed.mY>0) a.mSpeed.mY=0; b.bTop = true; if(b.mSpeed.mY<0) b.mSpeed.mY=0; } } As seen in my code it simply will not work. when object comes from right or left it doesn't work. I tried couple of ways other than this one but none worked. I am guessing right method will include mSpeed vector. But I have no idea how to do it. I really appreciate if you could help. Sorry for my bad english.

    Read the article

  • One-way platform collision

    - by TheBroodian
    I hate asking questions that are specific to my own code like this, but I've run into a pesky roadblock and could use some help getting around it. I'm coding floating platforms into my game that will allow a player to jump onto them from underneath, but then will not allow players to fall through them once they are on top, which require some custom collision detection code. The code I have written so far isn't working, the character passes through it on the way up, and on the way down, stops for a moment on the platform, and then falls right through it. Here is the code to handle collisions with floating platforms: protected void HandleFloatingPlatforms(Vector2 moveAmount) { //if character is traveling downward. if (moveAmount.Y > 0) { Rectangle afterMoveRect = collisionRectangle; afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y); foreach (World_Objects.GameObject platform in gameplayScreen.Entities) { if (platform is World_Objects.Inanimate_Objects.FloatingPlatform) { //wideProximityArea is just a rectangle surrounding the collision //box of an entity to check for nearby entities. if (wideProximityArea.Intersects(platform.CollisionRectangle) || wideProximityArea.Contains(platform.CollisionRectangle)) { if (afterMoveRect.Intersects(platform.CollisionRectangle)) { //This, in my mind would denote that after the character is moved, its feet have fallen below the top of the platform, but before he had moved its feet were above it... if (collisionRectangle.Bottom <= platform.CollisionRectangle.Top) { if (afterMoveRect.Bottom > platform.CollisionRectangle.Top) { //And then after detecting that he has fallen through the platform, reposition him on top of it... worldLocation.Y = platform.CollisionRectangle.Y - frameHeight; hasCollidedVertically = true; } } } } } } } } In case you are curious, the parameter moveAmount is found through this code: elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; float totalX = 0; float totalY = 0; foreach (Vector2 vector in velocities) { totalX += vector.X; totalY += vector.Y; } velocities.Clear(); velocity.X = totalX; velocity.Y = totalY; velocity.Y = Math.Min(velocity.Y, 1000); Vector2 moveAmount = velocity * elapsed;

    Read the article

  • Voronoi regions of a (convex) polygon.

    - by Xavura
    I'm looking to add circle-polygon collisions to my Separating Axis Theorem collision detection. The metanet software tutorial (http://www.metanetsoftware.com/technique/tutorialA.html#section3) on SAT, which I discovered in the answer to a question I found when searching, talks about voronoi regions. I'm having trouble finding material on how I would calculate these regions for an arbitrary convex polygon and aleo how I would determine if a point is in one + which. The tutorial does contain source code but it's a .fla and I don't have Flash unfortunately.

    Read the article

  • How to make a stack stable? Need help for an explicit resting contact scheme (2-dimensional)

    - by Register Sole
    Previously, I struggle with the sequential impulse-based method I developed. Thanks to jedediah referring me to this paper, I managed to rebuild the codes and implement the simultaneous impulse based method with Projected-Gauss-Seidel (PGS) iterative solver as described by Erin Catto (mentioned in the reference of the paper as [Catt05]). So here's how it currently is: The simulation handles 2-dimensional rotating convex polygons. Detection is using separating-axis test, with a SKIN, meaning closest points between two polygons is detected and determined if their distance is less than SKIN. To resolve collision, simultaneous impulse-based method is used. It is solved using iterative solver (PGS-solver) as in Erin Catto's paper. Error-correction is implemented using Baumgarte's stabilization (you can refer to either paper for this) using J V = beta/dt*overlap, J is the Jacobian for the constraints, V the matrix containing the velocities of the bodies, beta an error-correction parameter that is better be < 1, dt the time-step taken by the engine, and overlap, the overlap between the bodies (true overlap, so SKIN is ignored). However, it is still less stable than I expected :s I tried to stack hexagons (or squares, doesn't really matter), and even with only 4 to 5 of them, they would swing! Also note that I am not looking for a sleeping scheme. But I would settle if you have any explicit scheme to handle resting contacts. That said, I would be more than happy if you have a way of treating it generally (as continuous collision, instead of explicitly as a special state). Ideas I have tried: Using simultaneous position based error correction as described in the paper in section 5.3.2, turned out to be worse than the current scheme. If you want to know the parameters I used: Hexagons, side 50 (pixels) gravity 2400 (pixels/sec^2) time-step 1/60 (sec) beta 0.1 restitution 0 to 0.2 coeff. of friction 0.2 PGS iteration 10 initial separation 10 (pixels) mass 1 (unit is irrelevant for now, i modified velocity directly<-impulse method) inertia 1/1000 Thanks in advance! I really appreciate any help from you guys!! :) EDIT In response to Cholesky's comment about warm starting the solver and Baumgarte: Oh right, I forgot to mention! I do save the contact history and the impulse determined in this time step to be used as initial guess in the next time step. As for the Baumgarte, here's what actually happens in the code. Collision is detected when the bodies' closest distance is less than SKIN, meaning they are actually still separated. If at this moment, I used the PGS solver without Baumgarte, restitution of 0 alone would be able to stop the bodies, separated by a distance of ~SKIN, in mid-air! So this isn't right, I want to have the bodies touching each other. So I turn on the Baumgarte, where its role is actually to pull the bodies together! Weird I know, a scheme intended to push the body apart becomes useful for the reverse. Also, I found that if I increase the number of iteration to 100, stacks become much more stable, though the program becomes so slow. UPDATE Since the stack swings left and right, could it be something is wrong with my friction model? Current friction constraint: relative_tangential_velocity = 0

    Read the article

  • How do 2D physics engines solve the problem of resolving collisions along tiled walls/floors in non-grid-based worlds?

    - by ssb
    I've been working on implementing my SAT algorithm which has been coming along well, but I've found that I'm at a wall when it comes to its actual use. There are plenty of questions regarding this issue on this site, but most of them either have no clear, good answer or have a solution based on checking grid positions. To restate the problem that I and many others are having, if you have a tiled surface, like a wall or a floor, consisting of several smaller component rectangles, and you traverse along them with another rectangle with force being applied into that structure, there are cases where the object gets caught on a false collision on an edge that faces the inside of the shape. I have spent a lot of time thinking about how I could possibly solve this without having to resort to a grid-based system, and I realized that physics engines do this properly. What I want to know is how they do this. What do physics engines do beyond basic SAT that allows this kind of proper collision resolution in complex environments? I've been looking through the source code to Box2D trying to find out how they do it but it's not quite as easy as looking at a Collision() method. I think I'm not good enough at physics to know what they're doing mathematically and not good enough at programming to know what they're doing programmatically. This is what I aim to fix.

    Read the article

  • Simulating water droplets on a window

    - by skyuzo
    How do I simulate water droplets realistically falling, gathering, and flowing down a window? For example, see http://www.youtube.com/watch?v=4jaGyv0KRPw. In particular, I want to simulate how smaller droplets merge together to form larger droplets that have enough weight to oppose the surface tension and flow downward, leaving a trail of water. I'm aware of fluid simulation, but how would it be applied in this situation?

    Read the article

  • General purpose physics engine

    - by Lucas
    Is there any general purpose physics engine that allows huge simulations of rigid bodies? I'm using PhysX from Nvidia, but the focus of this engine is game development, soft bodies. I want to know if exists physics engine that runs on top of PS3 cell processors or CUDA cores allowing massive scientific physics simulations.

    Read the article

  • Problems with moving 2D circle/box collision detection

    - by dario3004
    This is my first game ever and I'm a newbie in computer physics. I've got this code for the collision detection and it works fine for BOTTOM and TOP collision.It miss the collision detection with the paddle's edge and angles so I've (roughly) tried to implement it. Main method that is called for bouncing, it checks if it bounce with wall, or with top (+ right/left side) or with bottom (+ right/left side): protected void handleBounces(float px, float py) { handleWallBounce(px, py); if(mBall.y < getHeight()/4){ if (handleRedFastBounce(mRed, px, py)) return; if (handleRightSideBounce(mRed,px,py)) return; if (handleLeftSideBounce(mRed,px,py)) return; } if(mBall.y > getHeight()/4 * 3){ if (handleBlueFastBounce(mBlue, px, py)) return; if (handleRightSideBounce(mBlue,px,py)) return; if (handleLeftSideBounce(mBlue,px,py)) return; } } This is the code for the BOTTOM bounce: protected boolean handleRedFastBounce(Paddle paddle, float px, float py) { if (mBall.goingUp() == false) return false; // next position tx = mBall.x; ty = mBall.y - mBall.getRadius(); // actual position ptx = px; pty = py - mBall.getRadius(); dyp = ty - paddle.getBottom(); xc = tx + (tx - ptx) * dyp / (ty - pty); if ((ty < paddle.getBottom() && pty > paddle.getBottom() && xc > paddle.getLeft() && xc < paddle.getRight())) { mBall.x = xc; mBall.y = paddle.getBottom() + mBall.getRadius(); mBall.bouncePaddle(paddle); playSound(mPaddleSFX); increaseDifficulty(); return true; } else return false; } As long as I understood it should be something like this: So I tried to make the "left side" and "right side" bounce method: protected boolean handleLeftSideBounce(Paddle paddle, float px, float py){ // next position tx = mBall.x + mBall.getRadius(); ty = mBall.y; // actual position ptx = px + mBall.getRadius(); pty = py; dyp = tx - paddle.getLeft(); yc = ty + (pty - ty) * dyp / (ptx - tx); if (ptx < paddle.getLeft() && tx > paddle.getLeft()){ System.out.println("left side bounce1"); System.out.println("yc: " + yc + "top: " + paddle.getTop() + " bottom: " + paddle.getBottom()); if (yc > paddle.getTop() && yc < paddle.getBottom()){ System.out.println("left side bounce2"); mBall.y = yc; mBall.x = paddle.getLeft() - mBall.getRadius(); mBall.bouncePaddle(paddle); playSound(mPaddleSFX); increaseDifficulty(); return true; } } return false; } I think I'm quite near to the solution but I'm having big troubles with the new "yc" formula. I tried so many versions of it but since I don't know the theory behind it I can't adjust for the Y axis. Since the Y axis is inverted I even tried this: yc = ty - (pty - ty) * dyp / (ptx - tx); I tried Googling it but I can't seem to find a solution for it. Also this method fails when ball touches the angle and I don't think is a nice way because it just test "one" point of the ball and probably there will be many cases in which the ball won't bounce.

    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

  • 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

  • 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

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >