Search Results

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

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

  • 2D SAT Collision Detection not working when using certain polygons

    - by sFuller
    My SAT algorithm falsely reports that collision is occurring when using certain polygons. I believe this happens when using a polygon that does not contain a right angle. Here is a simple diagram of what is going wrong: Here is the problematic code: std::vector<vec2> axesB = polygonB->GetAxes(); //loop over axes B for(int i = 0; i < axesB.size(); i++) { float minA,minB,maxA,maxB; polygonA->Project(axesB[i],&minA,&maxA); polygonB->Project(axesB[i],&minB,&maxB); float intervalDistance = polygonA->GetIntervalDistance(minA, maxA, minB, maxB); if(intervalDistance >= 0) return false; //Collision not occurring } This function retrieves axes from the polygon: std::vector<vec2> Polygon::GetAxes() { std::vector<vec2> axes; for(int i = 0; i < verts.size(); i++) { vec2 a = verts[i]; vec2 b = verts[(i+1)%verts.size()]; vec2 edge = b-a; axes.push_back(vec2(-edge.y,edge.x).GetNormailzed()); } return axes; } This function returns the normalized vector: vec2 vec2::GetNormailzed() { float mag = sqrt( x*x + y*y ); return *this/mag; } This function projects a polygon onto an axis: void Polygon::Project(vec2* axis, float* min, float* max) { float d = axis->DotProduct(&verts[0]); float _min = d; float _max = d; for(int i = 1; i < verts.size(); i++) { d = axis->DotProduct(&verts[i]); _min = std::min(_min,d); _max = std::max(_max,d); } *min = _min; *max = _max; } This function returns the dot product of the vector with another vector. float vec2::DotProduct(vec2* other) { return (x*other->x + y*other->y); } Could anyone give me a pointer in the right direction to what could be causing this bug?

    Read the article

  • 2D Rectangle Collision Response with Multiple Rectangles

    - by Justin Skiles
    Similar to: Collision rectangle response I have a level made up of tiles where the edges of the level are made up of collidable rectangles. The player's collision box is represented by a rectangle as well. The player can move in 8 directions. The player's velocity is equal in X and Y directions and constant. Each update, I am checking the player's collision against all tiles that are a certain distance away. When the player collides with a rectangle, I am finding the intersection depth and resolving along the most shallow axis followed by the other axis. This resolution happens for both axes simultaneously. See below for two examples of situations where I am having trouble. Moving up-left against the left wall In the scenario below, the player is colliding with two tiles. The tile intersection depth is equal on both axes for the top tile and more shallow in the X axis for the middle tile. Because the player is moving up the wall, the player should slide in an upward direction along the wall. This works properly as long as the rectangle with the more shallow depth is evaluated first. If the equal intersection depth rectangle is evaluated first, there is a chance the player becomes stuck. Moving up-left against the top wall Here is an identical scenario with the exception that the collision is with the top wall. The same problem occurs at the corners when intersection depth is equal for both axes. I guess my overall question is: How can I ensure that collision response occurs on tiles that have non-equal intersection depth before tiles that have equal intersection depth in order to get around the weirdness that occurs at these corners. Sean's answer in the linked question was good, but his solution required having different velocity components in a certain direction. My situation has equal velocities, so there's no good way to tell which direction to resolve at corners. I hope I have made my explanation clear.

    Read the article

  • 2D Platform Game Jumping

    - by Bradley Kreuger
    I'm currently writing a game in XNA for fun which uses C#. I have got my sprites loaded and when the character moves right he looks like he is running right and when he moves left he looks like he is running left. I been looking everywhere for a good coding example for how to create a jumping ability. I have read all the physics stuff that I can stand and it doesn't help when I can't figure out how to use say space bar to jump yet can't keep them from using space just jump again until they land.

    Read the article

  • Moving a body in a specific direction using XNA with Farseer Physics

    - by Code Assasssin
    I have a custom polygon attached to a body, which looks like this: What I am trying to accomplish is getting the body to move according to wherever the tip of the body is. So far this is what I've tried: if (ks.IsKeyDown(Keys.Up)) { body.ApplyForce(new Vector2(0, -20),body.GetLocalPoint(new Vector2(0,0))); } if (ks.IsKeyDown(Keys.Left)) { body.ApplyTorque(-500); } if (ks.IsKeyDown(Keys.Right)) { body.ApplyTorque(500); } The body rotates fine - but when I try making the body accelerate according to the tip of the body - assuming I have specified the tip correctly(I am pretty sure I haven't), it just spins around, as if I have applied Torque to it. Can anyone point me in the right direction of how to fix this problem?

    Read the article

  • 2D wave-like sprite movement XNA

    - by TheBroodian
    I'm trying to create a particle that will 'circle' my character. When the particle is created, it's given a random position in relation to my character, and a box to provide boundaries for how far left or right this particle should circle. When I use the phrase 'circle', I'm referring to a simulated circling, i.e., when moving to the right, the particle will appear in front of my character, when passing back to the left, the particle will appear behind my character. That may have been too much context, so let me cut to the chase: In essence, the path I would like my particle to follow would be akin to a sine wave, with the left and right sides of the provided rectangle being the apexes of the wave. The trouble I'm having is that the position of the particle will be random, so it will never be produced at the same place within the wave twice, but I have no idea how to create this sort of behavior procedurally.

    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

  • Find meeting point of 2 objects in 2D, knowing (constant) speed and slope

    - by Axonn
    I have a gun which fires a projectile which has to hit an enemy. The problem is that the gun has to be automatic, i.e. - choose the angle in which it has to shoot so that the projectile hits the enemy dead in the center. It's been a looooong time since school, and my physics skills are a bit rusty, but they're there. I've been thinking to somehow apply the v = d/t formula to find the time needed for the projectile or enemy to reach a certain point. But the problem is that I can't find the common point for both the projectile and enemy. Yes, I can find a certain point for the projectile, and another for the enemy, but I would need lots of tries to find where the point coincides, which is stupid. There has to be a way to link them together but I can't figure it out. I prepared some drawings and samples: A simple version of my Flash game, dumbed down to the basics, just some shapes: http://axonnsd.org/W/P001/MathSandBox.swf - click the mouse anywhere to fire a projectile. Or, here is an image which describes my problem: So... who has any ideas about how to find x3/y3 - thus leading me to find the angle in which the weapon has to tilt in order to fire a projectile to meet the enemy? EDIT I think it would be clearer if I also mention that I know: the speed of both Enemy and Projectile and the Enemy travels on a straight vertical line.

    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

  • XNA 4.0 2D sidescroller variable terrain heightmap for walking/collision

    - by JiminyCricket
    I've been fooling around with moving on sloped tiles in XNA and it is semi-working but not completely satisfactory. I also have been thinking that having sets of predetermined slopes might not give me terrain that looks "organic" enough. There is also the problem of having to construct several different types of tile for each slope when they're chained together (only 45 degree tiles will chain perfectly as I understand it). I had thought of somehow scanning for connected chains of sloped tiles and treating it as a new large triangle, as I was having trouble with glitching at the edges where sloped tiles connect. But, this leads back to the problem of limiting the curvature of the terrain. So...what I'd like to do now is create a simple image or texture of the terrain of a level (or section of the level) and generate a simple heightmap (of the Y's for each X) for the terrain. The player's Y position would then just be updated based on their X position. Is there a simple way of doing this (or a better way of solving this problem)? The main problem I can see with this method is the case where there are areas above the ground that can be walked on. Maybe there is a way to just map all walkable ground areas? I've been looking at this helpful bit of code: http://thirdpartyninjas.com/blog/2010/07/28/sloped-platform-collision/ but need a way to generate the actual points/vectors.

    Read the article

  • Smooth waypoint traversing

    - by TheBroodian
    There are a dozen ways I could word this question, but to keep my thoughts in line, I'm phrasing it in line with my problem at hand. So I'm creating a floating platform that I would like to be able to simply travel from one designated point to another, and then return back to the first, and just pass between the two in a straight line. However, just to make it a little more interesting, I want to add a few rules to the platform. I'm coding it to travel multiples of whole tile values of world data. So if the platform is not stationary, then it will travel at least one whole tile width or tile height. Within one tile length, I would like it to accelerate from a stop to a given max speed. Upon reaching one tile length's distance, I would like it to slow to a stop at given tile coordinate and then repeat the process in reverse. The first two parts aren't too difficult, essentially I'm having trouble with the third part. I would like the platform to stop exactly at a tile coordinate, but being as I'm working with acceleration, it would seem easy to simply begin applying acceleration in the opposite direction to a value storing the platform's current speed once it reaches one tile's length of distance (assuming that the tile is traveling more than one tile-length, but to keep things simple, let's just assume it is)- but then the question is what would the correct value be for acceleration to increment from to produce this effect? How would I find that value?

    Read the article

  • How to perform efficient 2D picking in HTML5?

    - by jSepia
    I'm currently using an R-Tree for both picking and collision testing. Each entity on screen has a bounding box for collisions and a separate one for picking. Since entities may change position very frequently, both trees must be updated/reordered once per frame. While this is very efficient for collisions, because the tree is used in hundreds of collision queries every frame, I'm finding it too costly for picking, because it only gets queried when the user clicks, thus leading to a lot of wasted tree updates. What would be a more efficient way to implement picking without as much overhead?

    Read the article

  • 2D game - Missile shooting problem on Android

    - by Niksa
    Hello, I have to make a tank that sits still but moves his turret and shoots missiles. As this is my first Android application ever and I haven't done any game development either, I've come across a few problems... Now, I did the tank and the moving turret once I read the Android tutorial for the LunarLander sample code. So this code is based on the LunarLander code. But I'm having trouble doing the missile firing then SPACE button is being pressed. private void doDraw(Canvas canvas) { canvas.drawBitmap(backgroundImage, 0, 0, null); // draws the tank canvas.drawBitmap(tank, x_tank, y_tank, new Paint()); // draws and rotates the tank turret canvas.rotate((float) mHeading, (float) x_turret + mTurretWidth, y_turret); canvas.drawBitmap(turret, x_turret, y_turret, new Paint()); // draws the grenade that is a regular circle from ShapeDrawable class bullet.setBounds(x_bullet, y_bullet, x_bullet + width, y_bullet + height); bullet.draw(canvas); } UPDATE GAME method private void updateGame() throws InterruptedException { long now = System.currentTimeMillis(); if (mLastTime > now) return; double elapsed = (now - mLastTime) / 1000.0; mLastTime = now; // dUP and dDown, rotates the turret from 0 to 75 degrees. if (dUp) mHeading += 1 * (PHYS_SLEW_SEC * elapsed); if (mHeading >= 75) mHeading = 75; if (dDown) mHeading += (-1) * (PHYS_SLEW_SEC * elapsed); if (mHeading < 0) mHeading = 0; if (dSpace){ // missile Logic, a straight trajectorie for now x_bullet -= 1; y_bullet -= 1; //doesn't work, has to be updated every pixel or what? } boolean doKeyDown(int keyCode, KeyEvent msg) { boolean handled = false; synchronized (mSurfaceHolder) { if (keyCode == KeyEvent.KEYCODE_SPACE){ dSpace = true; handled = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_UP){ dUp = true; handled = true; } if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){ dDown = true; handled = true; } return handled; } } } a method run that runs the game... public void run() { while (mRun) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { if (mMode == STATE_RUNNING) updateGame(); doDraw(c); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } So the question would be, how do I make that the bullet is fired on a single SPACE key press from the turret to the end of the screen? Could you help me out here, I seem to be in the dark here... Thanks, Niksa

    Read the article

  • 2D SAT Collision Detection not working when using certain polygons (With example)

    - by sFuller
    My SAT algorithm falsely reports that collision is occurring when using certain polygons. I believe this happens when using a polygon that does not contain a right angle. Here is a simple diagram of what is going wrong: Here is the problematic code: std::vector<vec2> axesB = polygonB->GetAxes(); //loop over axes B for(int i = 0; i < axesB.size(); i++) { float minA,minB,maxA,maxB; polygonA->Project(axesB[i],&minA,&maxA); polygonB->Project(axesB[i],&minB,&maxB); float intervalDistance = polygonA->GetIntervalDistance(minA, maxA, minB, maxB); if(intervalDistance >= 0) return false; //Collision not occurring } This function retrieves axes from the polygon: std::vector<vec2> Polygon::GetAxes() { std::vector<vec2> axes; for(int i = 0; i < verts.size(); i++) { vec2 a = verts[i]; vec2 b = verts[(i+1)%verts.size()]; vec2 edge = b-a; axes.push_back(vec2(-edge.y,edge.x).GetNormailzed()); } return axes; } This function returns the normalized vector: vec2 vec2::GetNormailzed() { float mag = sqrt( x*x + y*y ); return *this/mag; } This function projects a polygon onto an axis: void Polygon::Project(vec2* axis, float* min, float* max) { float d = axis->DotProduct(&verts[0]); float _min = d; float _max = d; for(int i = 1; i < verts.size(); i++) { d = axis->DotProduct(&verts[i]); _min = std::min(_min,d); _max = std::max(_max,d); } *min = _min; *max = _max; } This function returns the dot product of the vector with another vector. float vec2::DotProduct(vec2* other) { return (x*other->x + y*other->y); } Could anyone give me a pointer in the right direction to what could be causing this bug? Edit: I forgot this function, which gives me the interval distance: float Polygon::GetIntervalDistance(float minA, float maxA, float minB, float maxB) { float intervalDistance; if (minA < minB) { intervalDistance = minB - maxA; } else { intervalDistance = minA - maxB; } return intervalDistance; //A positive value indicates this axis can be separated. } Edit 2: I have recreated the problem in HTML5/Javascript: Demo

    Read the article

  • Big level objects collision system for 2d game

    - by Aristarhys
    I read many variants today and get some knowledge in general, so here is a steps of mine thoughts in pictures (horrible paint.net ones). We need to develop grid system, so we check only thing near, perform simple check to cut out deep check, and at - last deep check like per-pixel collision check. Step 1 - Let p1, p2 are some sprites lets first just check with circle collision - because large distance between p1, p2 this fails and of course so we don't need test more deeply. But if we have not 2, but 20 objects, why we need to even circle test something so far outside of our view. Step 2 - Add basic column system, now we don't bother with p2 if it's in a column far from p1 column, so we even don't do circle test. But p3 is in the same col, so let do circle test, which of course will fail. Step 3 - Lets improve column system to the grid system with grid cell size just like p1, p2, p3 collision boxes, so we cut out things much top or below p1. And this is all great until comes BIG OBJs which is some kind of platforms. They are much bigger then grid cell. Circle test for will be successful, but deep check for whole big obj will fail And that the part I can't get. How do I store the grid position of big object? Like 4 grid coords for big object vertexes? And if one of them close to p1 do circle check for centre of big object then a deep one if succeed? Am I do it wrong? My possible solution:

    Read the article

  • Almost working 2D Collisions

    - by TheGag96
    I'm terribly sorry I'm asking this question YET AGAIN, but I can almost guarantee that this will be the last time I'll have to ask. I'm currently on the verge of FINALLY getting these collisions to work for my game, made with libGDX in Java. My collisions use the same method as (and are basically copied and modified code from) the XNA Platformer example (here) where the direction of the collision is based on the rectangle where two objects are overlapping. The collisions themselves almost work perfectly, but for some reason, holding down/up and left and colliding with the floor/ceiling while doing so doesn't seem to work well. I'm not at all sure why. Instead of vaguely giving my problem and snippets of code, I've decided to instead provide a binary and the source of the game I have so far so you can see for yourself what my problem is. Link. (Note: make sure you unzip everything into a folder somewhere or it will not work) You'll find the collision code in the method workingCollisions() in Link.java. Please excuse the messy code and terrible graphics as this whole thing is in pre-pre-alpha. If anyone is kind enough and helps me out here, you are the best person ever. I'm completely desperate; I've been trying this on and off for months and I just can't get it to work. I cannot thank you enough.

    Read the article

  • Best way to mask 2D sprites in XNA?

    - by electroflame
    I currently am trying to mask some sprites. Rather than explaining it in words, I've made up some example pictures: The area to mask (in white) Now, the red sprite that needs to be cropped. The final result. Now, I'm aware that in XNA you can do two things to accomplish this: Use the Stencil Buffer. Use a Pixel Shader. I have tried to do a pixel shader, which essentially did this: float4 main(float2 texCoord : TEXCOORD0) : COLOR0 { float4 tex = tex2D(BaseTexture, texCoord); float4 bitMask = tex2D(MaskTexture, texCoord); if (bitMask.a > 0) { return float4(tex.r, tex.g, tex.b, tex.a); } else { return float4(0, 0, 0, 0); } } This seems to crop the images (albeit, not correct once the image starts to move), but my problem is that the images are constantly moving (they aren't static), so this cropping needs to be dynamic. Is there a way I could alter the shader code to take into account it's position? Alternatively, I've read about using the Stencil Buffer, but most of the samples seem to hinge on using a rendertarget, which I really don't want to do. (I'm already using 3 or 4 for the rest of the game, and adding another one on top of it seems overkill) The only tutorial I've found that doesn't use Rendertargets is one from Shawn Hargreaves' blog over here. The issue with that one, though is that it's for XNA 3.1, and doesn't seem to translate well to XNA 4.0. It seems to me that the pixel shader is the way to go, but I'm unsure of how to get the positioning correct. I believe I would have to change my onscreen coordinates (something like 500, 500) to be between 0 and 1 for the shader coordinates. My only problem is trying to work out how to correctly use the transformed coordinates. Thanks in advance for any help!

    Read the article

  • XNA 2D Spritesheet drawing rendering problem

    - by user24092
    I'm making a tile-based game, using one spritesheet containing all tile graphics. Each tile has a size of 32x32 pixels. The main problem is: when I draw the tile to the screen, if the tile position x and y are not rounded or if scale is activated in spriteBatch.Draw() method (scale != 1.0f), I get some lines of adjacent tiles on the spritesheet into the current tile drawed. I already tried setting SamplerState to PointClamp, removing AntiAlias, but still doesn't work. Here I'll show images of some tests that I made, with a test sprite sheet that I've created (I made a 9x9 spritesheet, with each sprite of size 32x32 containing a unique solid color). Tests: http://img6.imageshack.us/img6/5946/testsqj.png SpriteSheet used: http://imageshack.us/a/img821/1341/tilesm.png Already tried to remove anti-alias, set PointClamp as sampler state, but still getting this issue, XNA keeps drawing part of the adjacent pixels of the texture on the screen. What I want is to get the correct area of the tilesheet texture (as seen in the first test, that gets just the yellow pixels). My question is: Is there any way that I can fix this, WITHOUT adding tile spacing or any other modification involving the tilesheet? Maybe disabling a texture filtering that is done by XNA, or something like that.

    Read the article

  • How to create realistic 2d lighting using colour temperature

    - by Truncheon
    I'm looking for a lighting algorithm that produces realistic lights expressed in kelvins, from about 2500k to 6500k. What I'm confused about is how to make the lights properly interact with the colors of game objects. If a whole level is fully lit (overcast daylight) then it would seem that I should use just the color of the object. But what if I'm in a closed room with no windows, and there is an incandescent bulb shining light in the room? How would that light properly light up the objects in the room? There does not seem to be an obvious solution to the problem. And simply mixing the color of the light with the colors of the object, seems an inaccurate approach.

    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

  • Best approach to get clicked objects from a display list (2D)

    - by Ixx
    I'm implementing a display list to manage my visuals on screen. I want to know which object is clicked. My objects already have z-order variable. With my current knowledge (almost nothing) the only thing which comes to my mind is make a linear search and get all the objects which contains the clicked point. And then select the object with the highest z-order. But I know there are far better approaches. I think it's something with trees (binary search?). - container display objects and search recursively? just don't know where to start looking, for this concrete case. Any hint link or concrete solution is welcome.

    Read the article

  • Calculating the rotational force of a 2D sprite

    - by Jon
    I am wondering if someone has an elegant way of calculating the following scenario. I have an object of (n) number of squares, random shapes, but we will pretend they are all rectangles. We are dealing with no gravity, so consider the object in space, from a top down perspective. I am applying a force to the object at a specific square (as illustrated below). How do I calculate the rotational angle, based on the force being applied, at the location being applied. If applied in the center square, it would go straight. How should it behave the further I move from the center? How do I calculate the rotational velocity?

    Read the article

  • what is the easiest way to make a hitbox that rotates with it's texture

    - by Matthew Optional Meehan
    In xna when you have a sprite that doesnt rotate it's very easy to get the four corner of a sprite to make a hitbox, but when you do a rotation the points get moved and I assume there is some kind of math that I can use to aquire them. I am using the four points to draw a rectangle that visually represents the hitboxes. I have seen some per-pixel collission examples but I can forsee they would be hard to draw a box/'convex hull' around. I have also seen physics like farseer but I'm not sure if there is a quick tutorial to do what I want. What do you guys think is the best approach becuase I am looking to complete this work by the end of the week.

    Read the article

  • Rotating 2D Object

    - by Vico Pelaez
    Well I am trying to learn openGL and want to make a triangle move one unit (0.1) everytime I press one of the keyboard arrows. However i want the triangle to turn first pointing the direction where i will move one unit. So if my triangle is pointing up and I press right the it should point right first and then move one unit in the x axis. I have implemented the code to move the object one unit in any direction, however I can not get it to turn pointing to the direction it is going. The initial position of the Triangle is pointing up. #define LENGTH 0.05 float posX = -0.5, posY = -0.5, posZ = 0; float inX = 0.0 ,inY = 0.0 ,inZ = 0.0; // what values???? void rect(){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glPushMatrix(); glTranslatef(posX,posY,posZ); glRotatef(rotate, inX, inY, inZ); glBegin(GL_TRIANGLES); glColor3f(0.0, 0.0, 1.0); glVertex2f(-LENGTH,-LENGTH); glVertex2f(LENGTH-LENGTH, LENGTH); glVertex2f(LENGTH, -LENGTH); glEnd(); glPopMatrix(); } void display(){ //Clear Window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); rect(); glFlush(); } void init(){ glClearColor(0.0, 0.0, 0.0, 0.0); glColor3f(1.0, 1.0, 1.0); } float move_unit = 0.01; bool change = false; void keyboardown(int key, int x, int y) { switch (key){ case GLUT_KEY_UP: if(rotate = 0) posY += move_unit; else{ inX = 1.0; rotate = 0; } break; case GLUT_KEY_RIGHT: if(rotate = -90) posX += move_unit; else{ inX = 1.0; // is this value ok?? rotate -= 90; } break; case GLUT_KEY_LEFT: if(rotate = 90) posX -= move_unit; else{ inX = 1.0; // is this value ok??? rotate += 90; } break; case GLUT_KEY_DOWN: if(rotate = 180) posY -= move_unit; else{ inX = 1.0; rotate += 180; } break; case 27: // Escape button exit(0); break; default: break; } glutPostRedisplay(); } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0, 0); glutCreateWindow("Triangle turn"); glutSpecialFunc(keyboardown); glutDisplayFunc(display); init(); glutMainLoop()

    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

  • Collisions on complex map 2D

    - by waxx
    I'm currently thinking about collision and map system that I want to use in my next game and I'm kind of puzzled. Maps are going to be somewhat complex with lots of irregularities and thus tiling is out of question. I thought about an editor where you'd draw rectangles on the map that would represent areas that are collidable with and then saving such "collision map" with only black/white gfx. Or maybe should I save exact rectangles data with their x/y/width/height into some text file and go from there? What would you recommend? Thanks.

    Read the article

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