Search Results

Search found 3988 results on 160 pages for 'collision resolution'.

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

  • per pixel based collision detection.

    - by pengume
    I was wondering if anyone had any ideas on how to get per pixel collision detection for the android. I saw that the andEngine has great collision detection on rotation as well but couldn't see where the actual detection happened per pixel. Also noticed a couple solutions for java, could these be replicated for use with the Android SDK? Maybe someone here has a clean piece of code I could look at to help understand what is going on with per pixel detection and also why when rotating it is a different process.

    Read the article

  • Collision detection - Smooth wall sliding, no bounce effect

    - by Joey
    I'm working on a basic collision detection system that provides point - OBB collision detection. I have around 200 cubes in my environment and I check (for now) each of them in turn and see if it collides. If it does I return the colliding face's normal, save the old player position and do some trigonometry to return a new player position for my wall sliding. edit I'll define my meaning of wall sliding: If a player walks in a vertical slope and has a slight horizontal rotation to the left or the right and keeps walking forward in the wall the player should slide a little to the right/left while continually walking towards the wall till he left the wall. Thus, sliding along the wall. Everything works fine and with multiple objects as well but I still have one problem I can't seem to figure out: smooth wall sliding. In my current implementation sliding along the walls make my player bounce like a mad man (especially noticable with gravity on and moving forward). I have a velocity/direction vector, a normal vector from the collided plane and an old and new player position. First I negate the normal vector and get my new velocity vector by substracting the inverted normal from my direction vector (which is the vector to slide along the wall) and I add this vector to my new Player position and recalculate the direction vector (in case I have multiple collisions). I know I am missing some step but I can't seem to figure it out. Here is my code for the collision detection (run every frame): Vector direction; Vector newPos(camera.GetOriginX(), camera.GetOriginY(), camera.GetOriginZ()); direction = newPos - oldPos; // Direction vector // Check for collision with new position for(int i = 0; i < NUM_OBJECTS; i++) { Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z); if(normal != Vector::NullVector()) { // Get inverse normal (direction STRAIGHT INTO wall) Vector invNormal = normal.Negative(); Vector wallDir = direction - invNormal; // We know INTO wall, and DIRECTION to wall. Substract these and you got slide WALL direction newPos = oldPos + wallDir; direction = newPos - oldPos; } } Any help would be greatly appreciated! FIX I eventually got things up and running how they should thanks to Krazy, I'll post the updated code listing in case someone else comes upon this problem! for(int i = 0; i < NUM_OBJECTS; i++) { Vector normal = objects[i].CheckCollision(newPos.x, newPos.y, newPos.z, direction.x, direction.y, direction.z); if(normal != Vector::NullVector()) { Vector invNormal = normal.Negative(); invNormal = invNormal * (direction * normal).Length(); // Change normal to direction's length and normal's axis Vector wallDir = direction - invNormal; newPos = oldPos + wallDir; direction = newPos - oldPos; } }

    Read the article

  • Help with Collision of spawned object(postion fixed) with objects that there are translating on screen

    - by Amrutha
    Hey guys I am creating a game using Corona SDK and so coding it in Lua. So there are 2 separate functions, To translate the hit objects and change their color when they are tapped The link below is the code I am using to for the first function http://developer.anscamobile.com/sample-code/fishies Spawn objects that will hit the translating objects on collision. Alos on collision the spawned object disappears and the translating object bears a color(indicating the collision). In addition the size of this spawned object is dependent on i/p volume level. The function I have written is as follows: --VOICE INPUT CODE local r = media.newRecording() r:startRecording() r:startTuner() --local function newBar() -- local bar = display.newLine( 0, 0, 1, 0 ) -- bar:setColor( 0, 55, 100, 20 ) -- bar.width = 5 -- bar.y=400 -- bar.x=20 -- return bar --end local c1 = display.newImage("str-minion-small.png") c1.isVisible=false local c2 = display.newImage("str-minion-mid.png") c2.isVisible=false local c3 = display.newImage("str-minion-big.png") c3.isVisible=false --SPAWNING local function spawnDisk( event ) local phase = event.phase local volumeBar = display.newLine( 0, 0, 1, 0 ) volumeBar.y = 400 volumeBar.x = 20 --volumeBar.isVisible=false local v = 20*math.log(r:getTunerVolume()) local MINTHRESH = 30 local LEFTMARGIN = 20 local v2 = MINTHRESH + math.max (v, -MINTHRESH) v2 = (display.contentWidth - 1 * LEFTMARGIN ) * v2 / MINTHRESH volumeBar.xScale = math.max ( 20, v2 ) local l = volumeBar.xScale local cnt1 = 0 local cnt2 = 0 local cnt3 = 0 local ONE =1 local val = event.numTaps --local px=event.x --local py=event.y if "ended" == phase then --audio.play( popSound ) --myLabel.isVisible = false if l > 50 and l <=150 then --c1:setFillColor(10,105,0) --c1.isVisible=false c1.x=math.random( 10, 450 ) c1.y=math.random( 10, 300 ) physics.addBody( c1, { density=1, radius=10.0 } ) c1.isVisible=true cnt1= cnt1+ ONE return c1 elseif l > 100 and l <=250 then --c2:setFillColor(200,10,0) c2.x=math.random( 10, 450 ) c2.y=math.random( 10, 300 ) physics.addBody( c2, { density=2, radius=9000.0 } ) c2.isVisible=true cnt2= cnt2+ ONE return c2 elseif l >=250 then c3.x=math.random( 40, 450 ) c3.y=math.random( 40, 300 ) physics.addBody( c3, { density=2, radius=7000.0 , bounce=0.0 } ) c3.isVisible=true cnt3= cnt3+ ONE return c3 end end end buzzR:addEventListener( "touch", spawnDisk ) -- touch the screen to create disks Now both functions work fine independently but there is no collision happening. Its almost as if the translating object and the spawn object are on different layers. The translating object passes through the spawn object freely. Can anyone please tell me how to resolve this problem. And how can I get them to collide. Its my first attempt at game development, that too for a mobile platform so would appreciate all help. Also if I have not been specific do let me know. I'll try to frame the query better :). Thanks in advance.

    Read the article

  • Help with Collision of spawned object(postion fixed) with objects that there are translating on screen

    - by Amrutha
    Hey guys I am creating a game using Corona SDK and so coding it in Lua. So there are 2 separate functions, To translate the hit objects and change their color when they are tapped The link below is the code I am using to for the first function http://developer.anscamobile.com/sample-code/fishies Spawn objects that will hit the translating objects on collision. Alos on collision the spawned object disappears and the translating object bears a color(indicating the collision). In addition the size of this spawned object is dependent on i/p volume level. The function I have written is as follows, --VOICE INPUT CODE local r = media.newRecording() r:startRecording() r:startTuner() --local function newBar() -- local bar = display.newLine( 0, 0, 1, 0 ) -- bar:setColor( 0, 55, 100, 20 ) -- bar.width = 5 -- bar.y=400 -- bar.x=20 -- return bar --end local c1 = display.newImage("str-minion-small.png") c1.isVisible=false local c2 = display.newImage("str-minion-mid.png") c2.isVisible=false local c3 = display.newImage("str-minion-big.png") c3.isVisible=false --SPAWNING local function spawnDisk( event ) local phase = event.phase local volumeBar = display.newLine( 0, 0, 1, 0 ) volumeBar.y = 400 volumeBar.x = 20 -- volumeBar.isVisible=false local v = 20*math.log(r:getTunerVolume()) local MINTHRESH = 30 local LEFTMARGIN = 20 local v2 = MINTHRESH + math.max (v, -MINTHRESH) v2 = (display.contentWidth - 1 * LEFTMARGIN ) * v2 / MINTHRESH volumeBar.xScale = math.max ( 20, v2 ) local l = volumeBar.xScale local cnt1 = 0 local cnt2 = 0 local cnt3 = 0 local ONE =1 local val = event.numTaps --local px=event.x --local py=event.y if "ended" == phase then --audio.play( popSound ) --myLabel.isVisible = false if l > 50 and l <=150 then -- c1:setFillColor(10,105,0) -- c1.isVisible=false c1.x=math.random( 10, 450 ) c1.y=math.random( 10, 300 ) physics.addBody( c1, { density=1, radius=10.0 } ) c1.isVisible=true cnt1= cnt1+ ONE return c1 elseif l > 100 and l <=250 then --c2:setFillColor(200,10,0) c2.x=math.random( 10, 450 ) c2.y=math.random( 10, 300 ) physics.addBody( c2, { density=2, radius=9000.0 } ) c2.isVisible=true cnt2= cnt2+ ONE return c2 elseif l >=250 then c3.x=math.random( 40, 450 ) c3.y=math.random( 40, 300 ) physics.addBody( c3, { density=2, radius=7000.0 , bounce=0.0 } ) c3.isVisible=true cnt3= cnt3+ ONE return c3 end end end buzzR:addEventListener( "touch", spawnDisk ) -- touch the screen to create disks Now both functions work fine independently but there is no collision happening. Its almost as if the translating object and the spawn object are on different layers. The translating object passes through the spawn object freely. Can anyone please tell me how to resolve this problem. And how can I get them to collide. Its my first attempt at game development, that too for a mobile platform so would appreciate all help. Also if I have not been specific do let me know. I ll try to frame the query better :). Thanks in advance.

    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

  • Collision detection doesn't work for automated elements in XNA 4.0

    - by NDraskovic
    I have a really weird problem. I made a 3D simulator of an "assembly line" as a part of a college project. Among other things it needs to be able to detect when a box object passes in front of sensor. I tried to solve this by making a model of a laser and checking if the box collides with it. I had some problems with BoundingSpheres of models meshes so I simply create a BoundingSphere and place it in the same place as the model. I organized them into a list of BoundingSpheres called "spheres" and for each model I create one BoundingSphere. All models except the box are static, so the box object has its own BoundingSphere (not a member of the "spheres" list). I also implemented a picking algorithm that I use to start the movement. This is the code that checks for collision: if (spheres.Count != 0) { for (int i = 1; i < spheres.Count; i++) { if (spheres[i].Intersects(PickingRay) != null && Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton) { start = true; break; } if (BoxSphere.Intersects(spheres[i]) && start) { MoveBox(0, false);//The MoveBox function receives the direction (0) and a bool value that dictates whether the box should move or not (false means stop) start = false; break; } if (start /*&& Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton*/ && !BoxSphere.Intersects(spheres[i])) { MoveBox(0, true); break; } } The problem is this: When I use the mouse to move the box (the commented part in the third if condition) the collision works fine (I have another part of code that I removed to simplify my question - it calculates the "address" of the box, and by that number I know that the collision is correct). But when I comment it (like in this example) the box just passes trough the lasers and does not detect the collision (the idea is that the box stops at each laser and the user passes it forth by clicking on the appropriate "switch"). Can you see the problem? Please help, and if you need more informations I will try to give them. Thanks

    Read the article

  • Cocos2D - Detecting collision

    - by Grace
    I am a beginner in cocos2d and im facing a problem with detecting collision for my coins. Sometimes it works sometimes it doesn't. So basically, im creating a game which the user (ship) have to avoid the obstacles and collect coins on the way. The collision of the obstacle works well but not for the coins. I was thinking maybe the loops for creating many coins is the problem but im not sure. Can anyone help? My codes: - (void)update:(ccTime)dt{ double curTime = CACurrentMediaTime(); if (curTime > _nextBridgeSpawn) { float randSecs = [self randomValueBetween:3.0 andValue:5.0]; _nextBridgeSpawn = randSecs + curTime; float randX = [self randomValueBetween:50 andValue:500]; float randDuration = [self randomValueBetween:8.0 andValue:10.0]; CCSprite *bridge = [_bridge objectAtIndex:_nextBridge]; _nextBridge++; if (_nextBridge >= _bridge.count) _nextBridge = 0; [bridge stopAllActions]; bridge.position = ccp(winSize.width/2, winSize.height); bridge.visible = YES; [bridge runAction:[CCSequence actions: [CCMoveBy actionWithDuration:randDuration position:ccp(0, -winSize.height)], [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil]]; this is where i declare my coins (continued from the update method) int randCoin = [self randomValueBetween:0 andValue:5]; _coin = [[CCArray alloc] initWithCapacity:randCoin]; for(int i = 0; i < randCoin; ++i) { coin = [CCSprite spriteWithFile:@"coin.png"]; coin.visible = NO; [self addChild:coin]; [_coin addObject:coin]; } float randCoinX = [self randomValueBetween:winSize.width/5 andValue:winSize.width - (border.contentSize.width *2)]; float randCoinY = [self randomValueBetween:100 andValue:700]; float randCoinPlace = [self randomValueBetween:30 andValue:60]; for (int i = 0; i < _coin.count; ++i) { CCSprite *coin2 = [_coin objectAtIndex:i]; coin2.position = ccp(randCoinX, (bridge.position.y + randCoinY) + (randCoinPlace *i)); coin2.visible = YES; [coin2 runAction:[CCSequence actions: [CCMoveBy actionWithDuration:randDuration position:ccp(0, -winSize.height-2000)], [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil]]; } } this is to check for collision (also in the update method) for (CCSprite *bridge in _bridge) { if (!bridge.visible) continue; if (CGRectIntersectsRect(ship.boundingBox, bridge.boundingBox)){ bridge.visible = NO; [ship runAction:[CCBlink actionWithDuration:1.0 blinks:5]]; } } } //this is the collision for coins which only work at times for (CCSprite *coin2 in _coin) { if (!coin2.visible) continue; if (CGRectIntersectsRect(ship.boundingBox, coin2.boundingBox)) { NSLog(@"Coin collected"); coin2.visible = NO; } } } Thank you.

    Read the article

  • Viewing a large-resolution VNC server through a small-resolution viewer in Ubuntu

    - by Madiyaan Damha
    I have two Ubuntu computers, one with a large screen resolution (1920x1600) that is running default ubuntu vnc server. I have another computer that has a resolution of about 1200x1024 that I use to vnc into the server (I use the default ubuntu vnc viewer). Now everything works fine except there are annoying scrollbars in the viewer because the server's desktop resolution is so much higher than the viewer's. Is there a way to: 1) Scale the server's desktop down to the viewer's resolution. I know there will be a loss of image quality, but I am willing to try it out. This should be something like how windows media player or vlc scales down the window (and does some interpolation of pixels). 2) Automatically shrink the resolution of the server to the client's when I connect and scale the resolution back when I disconnect. This seems like a less attractive solution. 3) Any other solution that gurus out there use? I am sure someone has experienced this before (annoying scroll bars) so there must be a solution out there. Thanks,

    Read the article

  • 2D Platformer Collision Handling

    - by defender-zone
    Hello, everyone! I am trying to create a 2D platformer (Mario-type) game and I am some having some issues with handling collisions properly. I am writing this game in C++, using SDL for input, image loading, font loading, etcetera. I am also using OpenGL via the FreeGLUT library in conjunction with SDL to display graphics. My method of collision detection is AABB (Axis-Aligned Bounding Box), which is really all I need to start with. What I need is an easy way to both detect which side the collision occurred on and handle the collisions properly. So, basically, if the player collides with the top of the platform, reposition him to the top; if there is a collision to the sides, reposition the player back to the side of the object; if there is a collision to the bottom, reposition the player under the platform. I have tried many different ways of doing this, such as trying to find the penetration depth and repositioning the player backwards by the penetration depth. Sadly, nothing I've tried seems to work correctly. Player movement ends up being very glitchy and repositions the player when I don't want it to. Part of the reason is probably because I feel like this is something so simple but I'm over-thinking it. If anyone thinks they can help, please take a look at the code below and help me try to improve on this if you can. I would like to refrain from using a library to handle this (as I want to learn on my own) or the something like the SAT (Separating Axis Theorem) if at all possible. Thank you in advance for your help! void world1Level1CollisionDetection() { for(int i; i < blocks; i++) { if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==true) { int up = 0; int left = 0; int right = 0; int down = 0; if(ball.coords[0] < block[i].coords[0] && block[i].coords[0] < ball.coords[2] && ball.coords[2] < block[i].coords[2]) { left = 1; } if(block[i].coords[0] < ball.coords[0] && ball.coords[0] < block[i].coords[2] && block[i].coords[2] < ball.coords[2]) { right = 1; } if(ball.coords[1] < block[i].coords[1] && block[i].coords[1] < ball.coords[3] && ball.coords[3] < block[i].coords[3]) { up = 1; } if(block[i].coords[1] < ball.coords[1] && ball.coords[1] < block[i].coords[3] && block[i].coords[3] < ball.coords[3]) { down = 1; } cout << left << ", " << right << ", " << up << ", " << down << ", " << endl; if (left == 1) { ball.coords[0] = block[i].coords[0] - 16.0f; ball.coords[2] = block[i].coords[0] - 0.0f; } if (right == 1) { ball.coords[0] = block[i].coords[2] + 0.0f; ball.coords[2] = block[i].coords[2] + 16.0f; } if (down == 1) { ball.coords[1] = block[i].coords[3] + 0.0f; ball.coords[3] = block[i].coords[3] + 16.0f; } if (up == 1) { ball.yspeed = 0.0f; ball.gravity = 0.0f; ball.coords[1] = block[i].coords[1] - 16.0f; ball.coords[3] = block[i].coords[1] - 0.0f; } } if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==false) { ball.gravity = -0.5f; } } } To explain what some of this code means: The blocks variable is basically an integer that is storing the amount of blocks, or platforms. I am checking all of the blocks using a for loop, and the number that the loop is currently on is represented by integer i. The coordinate system might seem a little weird, so that's worth explaining. coords[0] represents the x position (left) of the object (where it starts on the x axis). coords[1] represents the y position (top) of the object (where it starts on the y axis). coords[2] represents the width of the object plus coords[0] (right). coords[3] represents the height of the object plus coords[1] (bottom). de2dCheckCollision performs an AABB collision detection. Up is negative y and down is positive y, as it is in most games. Hopefully I have provided enough information for someone to help me successfully. If there is something I left out that might be crucial, let me know and I'll provide the necessary information. Finally, for anyone who can help, providing code would be very helpful and much appreciated. Thank you again for your help!

    Read the article

  • Continuous Physics Engine's Collision Detection Techniques

    - by Griffin
    I'm working on a purely continuous physics engine, and I need to choose algorithms for broad and narrow phase collision detection. "Purely continuous" means I never do intersection tests, but instead want to find ways to catch every collision before it happens, and put each into "planned collisions" stack that is ordered by TOI. Broad Phase The only continuous broad-phase method I can think of is encasing each body in a circle and testing if each circle will ever overlap another. This seems horribly inefficient however, and lacks any culling. I have no idea what continuous analogs might exist for today's discrete collision culling methods such as quad-trees either. How might I go about preventing inappropriate and pointless broad test's such as a discrete engine does? Narrow Phase I've managed to adapt the narrow SAT to a continuous check rather than discrete, but I'm sure there's other better algorithms out there in papers or sites you guys might have come across. What various fast or accurate algorithm's do you suggest I use and what are the advantages / disatvantages of each? Final Note: I say techniques and not algorithms because I have not yet decided on how I will store different polygons which might be concave, convex, round, or even have holes. I plan to make a decision on this based on what the algorithm requires (for instance if I choose an algorithm that breaks down a polygon into triangles or convex shapes I will simply store the polygon data in this form).

    Read the article

  • 2D Side Scrolling game and "walk over ground" collision detection

    - by Fire-Dragon-DoL
    The question is not hard, I'm writing a game engine for 2D side scrolling games, however I'm thinking to my 2D side scrolling game and I always come up with the problem of "how should I do collision with the ground". I think I couldn't handle the collision with ground (ground for me is "where the player walk", so something heavily used) in a per-pixel way, and I can't even do it with simple shape comparison (because the ground can be tilted), so what's the correct way? I'know what tiles are and i've read about it, but how much should be big each tile to not appear like a stairs?Are there any other approach? I watched this game and is very nice how he walks on ground: http://www.youtube.com/watch?v=DmSAQwbbig8&feature=player_embedded If there are "platforms" in mid air, how should I handle them?I can walk over them but I can't pass "inside". Imagine a platform in mid air, it allows you to walk over it but limit you because you can't jump in the area she fits Sorry for my english, it's not my native language and this topic has a lot of keywords I don't know so I have to use workarounds Thanks for any answer Additional informations and suggestions: I'm doing a game course in this period and I asked them how to do this, they suggested me this approach (a QuadTree): -All map is divided into "big nodes" -Each bigger node has sub nodes, to find where the player is -You can find player's node with a ray on player position -When you find the node where the player is, you can do collision check through all pixels (which can be 100-200px nothing more) Here is an example, however i didn't show very well the bigger nodes because i'm not very good with photoshop :P How is this approach?

    Read the article

  • Camera Collision inside the room model

    - by sanddy
    I am having a problem in Calculating the camera collision for my Room model which consists of sofa, tables and other models. The users shall be moving the camera front, back, rotating so i need to make sure that the camera does not collide with any of the models with in the room. I have treated all my models inside the room by BoundingBox[] and the camera by BoundingSphere. So, far i have implemented collision by looking into the tutorial from http://www.toymaker.info/Games/XNA/html/xna_model_collisions.html which was great. But, I guess the problem lies in the Transformation part. I debugged and found some points to be at Vector(-XXX,-XXX,-XXX) where X is digit. Also i found my radius of some models where too large(in thousand, i just looked into its radius value before converting to BoundingBox). Do I need to scale the model for collision??? Below are my code:- On My LoadContent(): Matrix[] transforms = new Matrix[myModel.Bones.Count]; myModel.CopyAbsoluteBoneTransformsTo(transforms); int index = 0; box = new List<BoundingBox>(); BoundingBox worldModel = Utility.CalculateBoundingBox(myModel); foreach (ModelMesh mesh in myModel.Meshes) { Vector3[] obb = new Vector3[8]; worldModel.GetCorners(obb); Vector3[] asdf = (Vector3[])obb.Clone(); Vector3.Transform(obb, ref transforms[mesh.ParentBone.Index], obb); BoundingBox worldBox = BoundingBox.CreateFromPoints(obb); box.Add(worldBox); index++; } On CameraPosition Update: BoundingSphere bs = new BoundingSphere(this.cameraPos, 5.0f); if (RoomWalkthrough.Utility.CheckCollision(bs, bb)) { // Do Something } Please Help.

    Read the article

  • improve Collision detection memory usage (blocks with bullets)

    - by Eddy
    i am making a action platform 2D game, something like Megaman. I am using XNA to make it. already made player phisics,collisions, bullets, enemies and AIs, map editor, scorolling X Y camera (about 75% of game is finished ). as i progressed i noticed that my game would be more interesting to play if bullets would be destroyed on collision with regular(stationary ) map blocks, only problem is that if i use my collision detection (each bullet with each block) sometimes it begins to lag(btw if my bullet exits the screen player can see it is removed from bullet list) So how to improve my collision detection so that memory usage would be so high? :) ( on a map 300x300 blocks for example don't think that bigger map should be made); int block = 0; int bulet= 0; bool destroy_bullet = false; while (bulet < bullets.Count) { while (block < blocks.Count) { if (bullets[bulet].P_Bul_rec.Intersects( blocks[block].rect)) {//bullets and block are Lists that holds objects of bullet and block classes //P_Bul_rec just bullet rectangle destroy_bullet = true; } block++; } if (destroy_bullet) { bullets.RemoveAt(bulet); destroy_bullet = false; } else { bulet++; } block = 0; }

    Read the article

  • Circle to Circle collision, checking each circle against all others

    - by user14861
    I'm currently coding a little circle to circle collision demo but I've got a little stuck. I think I currently have the code to detect collision but I'm not sure how to loop through my list of circles and check them off against one another. Collision check code: public static Vector2 GetIntersectionDepth(Circle a, Circle b) { float xValue = a.Center.X - b.Center.X; float yValue = a.Center.Y - b.Center.Y; Vector2 depth = Vector2.Zero; float distance = Vector2.Distance(a.Center, b.Center); if (a.Radius + b.Radius > distance) { float result = (a.Radius + b.Radius) - distance; depth.X = (float)Math.Cos(result); depth.Y = (float)Math.Sin(result); } return depth; } Loop through code: Vector2 depth = Vector2.Zero; for (int i = 0; i < bounds.Count; i++) for (int j = i+1; j < bounds.Count; j++) { depth = CircleToCircleIntersection.GetIntersectionDepth(bounds[i], bounds[j]); } Clearly I'm a complete newbie, wondering if anyone can give any suggestions or point out my errors, thanks in advance. :)

    Read the article

  • LWJGL Java 2D collision when lagging

    - by user1990950
    I'm using a tile based collision, but when the game is lagging (the lag isn't the problem) the collision fails and the player falls through tiles. This is the movement/collision detection code of my Player class: gravity.y = gspeed; speed.y+=gravity.y; position.set(position.x + direction.x * speed.x * deltaSeconds, position.y + direction.y * speed.y * deltaSeconds); for (int i = (int) Math.round(position.x / 32) - 2 * t; i < (int) Math.round(position.x / 32) + 3 * t; i++) { for (int j = (int) Math.round(position.y / 32); j < (int) Math.round((position.y + height + 64) / 32); j++) { checkCollision(i, j, deltaSeconds); } } public void checkCollision(int i, int j, float deltaSeconds) { bbox.setBounds((int) position.x, (int) position.y, (int) width, (int) height); Tile t = null; t = Map.getTile(i, j); if (t != null) { if (t.isSolid()) { if (t.getTop().intersects(bbox)) { if (position.y + height < t.y * 32 + 32) { if (speed.y >= 0) { position.y = t.y * 32 - height; speed.y = 0; gravity.y = 0; jumpState = 0; } } } if (t.getBottom().intersects(bbox)) { if (position.y < t.y * 32 + 32) { position.y = t.y * 32 + 32; speed.y = 0; } } else { if (t.getLeft().intersects(bbox)) { if (position.x + width > t.x * 32) { position.x = t.x * 32 - width; speed.x = 0; } } if (t.getRight().intersects(bbox)) { if (position.x < t.x * 32 + 32) { position.x = t.x * 32 + 32; speed.x = 0; } } } } } } Is it possible to fix my code, if yes how? Or is it possible to tell if the game is lagging?

    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

  • Colored Collision Detection

    - by tugrul büyükisik
    Several years ago, i made a fast collision detection for 2D, it was just checking a bullets front-pixel's color to check if it were to hit something. Lets say the target rgb color is (124,200,255) then it just checks for that color. After the collision detection, it paints the target with appropriate picture. So, collision detection is made in background without drawing but then painted and drawed. How can i do this in 3D? Because, a vertex is not just exist like a 2D picture's pixel. I looked at some java3D and other programs and understood that 3D world is made of objects. Not just pictures. Is there a program that truly fills the world with vertices ? But it could be needing terabytes of ram even more. Do you know an easy way to interpolate the color of a vertex in java3D or similar program? Note: for a rgb color-identifier, i can make 255*255*255 different 2D objects in background.

    Read the article

  • Android Bitmap: Collision Detecting

    - by Aekasitt Guruvanich
    I am writing an Android game right now and I would need some help in the collision of the Pawns on screen. I figured I could run a for loop on the Player class with all Pawn objects on the screen checking whether or not Width*Height intersects with each other, but is there a more efficient way to do this? And if you do it this way, many of the transparent pixel inside the rectangular area will also be considered as collision as well. Is there a way to check for collision between Bitmap on a Canvas that disregard transparent pixels? The class for player is below and the Pawn class uses the same method of display. Class Player { private Resources res; // Used for referencing Bitmap from predefined location private Bounds bounds; // Class that holds the boundary of the screen private Bitmap image; private float x, y; private Matrix position; private int width, height; private float velocity_x, velocity_y; public Player (Resources resources, Bounds boundary) { res = resources; bounds = boundary; image = BitmapFactory.decodeResource(res, R.drawable.player); width = image.getWidth(); height = image.getHeight(); position = new Matrix(); x = bounds.xMax / 2; // Initially puts the Player in the middle of screen y = bounds.yMax / 2; position.preTranslate(x,y); } public void draw(Canvas canvas) { canvas.drawBitmap(image, position, null); } }

    Read the article

  • Updating entities in response to collisions - should this be in the collision-detection class or in the entity-updater class?

    - by Prog
    In a game I'm working on, there's a class responsible for collision detection. It's method detectCollisions(List<Entity> entities) is called from the main gameloop. The code to update the entities (i.e. where the entities 'act': update their positions, invoke AI, etc) is in a different class, in the method updateEntities(List<Entity> entities). Also called from the gameloop, after the collision detection. When there's a collision between two entities, usually something needs to be done. For example, zero the velocity of both entities in the collision, or kill one of the entities. It would be easy to have this code in the CollisionDetector class. E.g. in psuedocode: for(Entity entityA in entities){ for(Entity entityB in entities){ if(collision(entityA, entityB)){ if(entityA instanceof Robot && entityB instanceof Robot){ entityA.setVelocity(0,0); entityB.setVelocity(0,0); } if(entityA instanceof Missile || entityB instanceof Missile){ entityA.die(); entityB.die(); } } } } However, I'm not sure if updating the state of entities in response to collision should be the job of CollisionDetector. Maybe it should be the job of EntityUpdater, which runs after the collision detection in the gameloop. Is it okay to have the code responding to collisions in the collision detection system? Or should the collision detection class only detect collisions, report them to some other class and have that class affect the state of the entities?

    Read the article

  • simple collision detection with box2dweb

    - by skywalker
    im beginner in box2dweb that version of box2d for javascript i wrote simple gravity system and i want to detect the collision between the box and the ground , when the falling box hit the ground execute simple function like function sucs(){alert("the box on the floor !")}; this is my code var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30; var b2Vec2 = Box2D.Common.Math.b2Vec2 , b2BodyDef = Box2D.Dynamics.b2BodyDef , b2Body = Box2D.Dynamics.b2Body , b2FixtureDef = Box2D.Dynamics.b2FixtureDef , b2Fixture = Box2D.Dynamics.b2Fixture , b2World = Box2D.Dynamics.b2World , b2MassData = Box2D.Collision.Shapes.b2MassData , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape , b2DebugDraw = Box2D.Dynamics.b2DebugDraw; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var world = new b2World(new b2Vec2(0, 8), true); var fixDef = new b2FixtureDef(); var bodyDef = new b2BodyDef(); fixDef.density = 1.0; fixDef.friction = 0.5; bodyDef.type = b2Body.b2_staticBody; fixDef.shape = new b2PolygonShape; fixDef.shape.SetAsBox(20, 2); bodyDef.position.Set(10, 400 / 30 + 1.8); world.CreateBody(bodyDef).CreateFixture(fixDef); fixDef.density = 1.0; fixDef.friction = 0.5; fixDef.restitution = 0.3; bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.Set(50 / SCALE, 0 / SCALE); //bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2); fixDef.shape = new b2PolygonShape(); fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE); world.CreateBody(bodyDef).CreateFixture(fixDef); var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")); debugDraw.SetDrawScale(30.0); debugDraw.SetFillAlpha(0.5); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); var image = new Image(); image.src = "image.png"; window.setInterval(gameLoop, 1000 / 60); function gameLoop() { world.Step(1 / 60, 8, 3); world.ClearForces(); context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); b = world.GetBodyList() var pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); b = b.GetNext(); pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); //b.GetAngle()++; context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); world.DrawDebugData(); };

    Read the article

  • 2D Tile based Game Collision problem

    - by iNbdy
    I've been trying to program a tile based game, and I'm stuck at the collision detection. Here is my code (not the best ^^): void checkTile(Character *c, int **map) { int x1,x2,y1,y2; /* Character position in the map */ c->upY = (c->y) / TILE_SIZE; // Top left corner c->downY = (c->y + c->h) / TILE_SIZE; // Bottom left corner c->leftX = (c->x) / TILE_SIZE; // Top right corner c->rightX = (c->x + c->w) / TILE_SIZE; // Bottom right corner x1 = (c->x + 10) / TILE_SIZE; // 10px from left side point x2 = (c->x + c->w - 10) / TILE_SIZE; // 10px from right side point y1 = (c->y + 10) / TILE_SIZE; // 10px from top side point y2 = (c->y + c->h - 10) / TILE_SIZE; // 10px from bottom side point /* Top */ if (map[c->upY][x1] > 2 || map[c->upY][x2] > 2) c->topCollision = 1; else c->topCollision = 0; /* Bottom */ if ((map[c->downY][x1] > 2 || map[c->downY][x2] > 2)) c->downCollision = 1; else c->downCollision = 0; /* Left */ if (map[y1][c->leftX] > 2 || map[y2][c->leftX] > 2) c->leftCollision = 1; else c->leftCollision = 0; /* Right */ if (map[y1][c->rightX] > 2 || map[y2][c->rightX] > 2) c->rightCollision = 1; else c->rightCollision = 0; } That calculates 8 collision points My moving function is like that: void movePlayer(Character *c, int **map) { if ((c->dirX == LEFT && !c->leftCollision) || (c->dirX == RIGHT && !c->rightCollision)) c->x += c->vx; if ((c->dirY == UP && !c->topCollision) || (c->dirY == DOWN && !c->downCollision)) c->y += c->vy; checkPosition(c, map); } and the checkPosition: void checkPosition(Character *c, int **map) { checkTile(c, map); if (c->downCollision) { if (c->state != JUMPING) { c->vy = 0; c->y = (c->downY * TILE_SIZE - c->h); } } if (c->leftCollision) { c->vx = 0; c->x = (c->leftX) * TILE_SIZE + TILE_SIZE; } if (c->rightCollision) { c->vx = 0; c->x = c->rightX * TILE_SIZE - c->w; } } This works, but sometimes, when the player is landing on ground, right and left collision points become equal to 1. So it's as if there were collision coming from left or right. Does anyone know why this is doing this?

    Read the article

  • Resolving bounding box collision detection

    - by ndg
    I'm working on a simple collision detection and resolution method for a 2d tile-based bounding box system. Collision appears to work correctly, but I'm having issues with resolving a collision after it has happened. Essentially what I'm attempting to do is very similar to this approach. The problem I'm experiencing is that because objects can be traveling with both horizontal and vertical velocity, my resolution code causes the object to jump incorrectly. I've drawn the following annotation to explain my issue. In this example, because my object has both horizontal and vertical velocity, my object (which is heading upwards and collides with the bottom of a tile) has it's position altered twice: To correctly adjust it's vertical position to be beneath the tile. To incorrectly adjust it's horizontal position to be to the left of the tile. Below is my collision/resolution code in full: function intersects(x1, y1, w1, h1, x2, y2, w2, h2) { w2 += x2; w1 += x1; if (x2 > w1 || x1 > w2) return false; h2 += y2; h1 += y1; if (y2 > h1 || y1 > h2) return false; return true; } for(var y = 0; y < this.game.level.tiles.length; y++) { for(var x = 0; x < this.game.level.tiles[y].length; x++) { var tile = this.game.level.getTile(x, y); if(tile) { if( this.velocity.x > 0 && intersects(this.position.x+dx+this.size.w, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.x = ((x*tileSize)-this.size.w); hitSomething = true; break; } else if( this.velocity.x < 0 && intersects(this.position.x+dx, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.x = ((x*tileSize)+tileSize); hitSomething = true; break; } if( this.velocity.y > 0 && intersects(this.position.x+dx, this.position.y+dy+this.size.h, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.y = ((y*tileSize)-this.size.h); hitSomething = true; break; } else if( this.velocity.y < 0 && intersects(this.position.x+dx, this.position.y+dy, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize) ) { this.position.y = ((y*tileSize)+tileSize); hitSomething = true; break; } } } } if(hitSomething) { this.velocity.x = this.velocity.y = 0; dx = dy = 0; this.setJumping(false); }

    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

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