Fast 2D collision detection in an unbounded space I'm trying to do collision detection on a large number of entities of greatly varying size in an unbounded space. The entities are circles, so it's relatively easy to check if two are colliding. However, with a large number of entities the simulations slows down a lot when I code it to check every entity against every other (for n entities, I believe it is n (n 1) 2 checks, way too many!) Here's my though process so far First, I considered using a grid of some sort, like described in steps 1 2 of the answer here Fast, accurate 2d collision There are, however, a few problems with this 1) It is an unbounded space. Where do I start and end the grid? How do I determine the size of each square in the grid in a world where some objects are literally tens of millions times larger the other objects? 2) Even if I somehow manage to adjust the size of the grid every frame without using too much processing power, so that it adjust to fit the most distant objects, (unlikely that I could do this efficiently) this is still not a solution. If tons of objects are clustered in a 10,000x10,000 space, and one object goes shooting off into space 100 billion units of distance away, the grid would "zoom out", leaving all of the objects in the smaller 10,000x10,000 space in one square, which would defeat the purpose of making a grid in the first place. For these reasons, I'm thinking that a simple grid is not the best idea... I looked at BSP's, and I admit that I don't fully understand the concept, but it seems like it does not apply well to my situation (especially since I am using circles and BSP seems better suited to a more complicated polygonal world). Quad trees seem promising (something like this perhaps http www.youtube.com watch?v qJJnzSLrC1E) but I foresee at least two potential issues 1) I can calculate the "farthest away objects" each frame to give calculate GreatestXValue, LeastXValue, GreatestYValue, and LeastYValue, for each frame. From that I have a rectangle to work with that contains all entities. However, I will have to redo this each frame, which means that I have recreate the the entire quadtree each frame no shortcuts on calculations done in previous frames. Is this a problem or do most game simulation programmers have to completely recreate the quadtree each frame anyway? 2) (Probably the bigger problem) How do I handle a massive object in the vincinity of many small objects? Think about many circles with radius 5 being very close to, resting against, or colliding with a circle with radius 100,000. That massive object will be in many, many grid squares, and it seems to me that the situation would force the creation of a tree that is far too broad and deep. Am I on the right track with my thought process? Where do I go from here? Thank you very much for your time and help!!


Godot raycast colliding too high I am making an fps that uses a raycast for shooting. I used some suggestions taken from a few reddit pages, but it's mostly my own code. It was working properly, until I noticed that when you shot up above the enemy, it still registered as a hit. Does anyone know why this might be happening? code func use weapon() Raycast.force raycast update() if Raycast.is colliding() var collider Raycast.get collider() if collider if collider.has method( quot takedamage quot ) collider.takedamage(10)


Slopes vs. Rectangles Different Collision Points My platformer has both rectangular tiles and right triangle slopes with rectangular hitboxes. My sprites are also rectangular. Collision with only rectangular tiles works well. Even if there are multiple rectangular tiles, collision still works pretty well. Sprites can collide with individual slopes correctly as well, however, they collide at a different point. In order for the character's feet to be walking down the slope instead of hovering over it, the collision point for slopes is the bottom center point. For rectangles, it is either corner. The problem is moving from a rectangular tile onto a sloped one. The sprite resolves by the corners first, since it is resting atop a rectangular tile. However, the center point is resting above the slope, and the sprite will not move onto the slope until it is entirely moved off of the rectangular tile. Here's a diagram How can I reliably use two different collision points for different tiles in a way that allows sprites to walk between rectangular and sloped tiles?


Collision detection formula for getting intersection point I need help with collision detection algorithm from this paper http www.peroxide.dk papers collision collision.pdf I assume I am colliding with sphere of radius 1, just to make everything not important easier...I am concerned with formula, which finds intersection point with plane (page 14) planeIntersectionPoint basePoint planeNormal t0 velocity where basePoint center of Sphere planeNormal normalized normal vector to colliding plane t0 number from 0,1 interval, first moment from this interval during which collision happens, assuming we are moving with velocity vector velocity velocity vector I think that this formula doesn't work... Assuming that I am already intersecting with plane at t0 0, I just get planeIntersectionPoint basePoint planeNormal What gives me point which doesn't even belong to plane, what fails further parts of the algorithm, when I check if intersection point is in triangle... I will be grateful for every answer... Is the algorithm wrong, or that's me misunderstanding something?...


How is raycasting implemented I know what it's used for, I know what it does. What I am essentially asking is what is the math code behind how it works? I'm aware that any custom implementation would likely be slower than an engines official implementation, I just am interested in how it works.


Roguelike 2D Collision Detection I'm just a normal guy trying to do some basic collision detection but I suck at it. I either get stuck in a wall or I go in reverse in the wrong direction trying to update the player position to a non collision part. So here is how I check for collision and this function will return true or false. True if collision and false if not. roguelike.player.collision function() var player roguelike.player for(var i 0 i lt roguelike.map.rooms.length i ) var room roguelike.map.rooms i if(player.x gt room.x amp amp player.x lt room.x room.width amp amp player.y gt room.y amp amp player.y lt room.y room.height) return false return true This function works just fine just like expected. But it's when I try to stop the player when he hits a wall is where I get bugs. When the player goes down and hits a wall he gets stuck there. Here is the function that updates the player position. roguelike.update function() var player roguelike.player Left if(player.moving.left amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Up if(player.moving.up amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Right if(player.moving.right amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() down if(player.moving.down amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() player.savePosition() So what I do is check what direction the player is moving and if there is no collision detected then the player is free to move. Otherwise if there is a collision I put the player position as the last position he was when there was no collision so he will be free to move. This works going left, up, and right, but not going down. Going down the player gets stuck in the collision and the resetPosition function doesn't put the player back in the safe zone. So I know there must be a better way. And I would appreciate your advice on what you think that way should be.


How do Axis Aligned Bounding Boxes update with rotations? I have a bounding box class with a min (x,y,z) and max point (x,y,z). The object that is being rotated has a rotation matrix (3x3 matrix), but I don't know how to update the bounding box with rotations. I'm also a little confused if I should be using Oriented Bounding Boxes instead. For example, if the 3D object is a cube then the bounding box would rotate with it so they share the same 8 vertices at whatever rotation the cube is in. What's the best way to represent the bounding box for rotations and test for collisions?


Support function of Minkowski Difference I am watching this and if you stop at 7 25, you will find an implementation of the support function. The goal of the function is to give you the farthest point in a given direction. My question is how do we achieve this without looking at all the points in the Minkowski Difference? How is this not an O(m n) algorithm ? Is there a way to get just the points that lie on the edges (I am asking because in the slide after that he just shows the edge points and not all the internal ones)? Am I missing something ?


2D Distance Field as collision handler method Pixeljunk Shooter has really cool fluid simulation. I found the dev's video explaining what they did. Here I understand that it is particle based simulation Smoothed Particle Hydrodynamic I can find adequate resources and even books covering this topic, but I can't find resources for the "collision" All I can find about using distance field for collision are very tough article and some vague description The second resource states Using a signed distance field then makes it very easy to check if a particle is colliding with our environment simply sample the distance field at the particle position and if the magnitude of the distance is negative we have a collision (ignoring the potential for tunneling for the time being). Once a collision is detected we can then backtrack along the particle trajectory until we find where the particle collided with the surface. To calculate the collision response we then need to determine the surface normal this is again easy as we simply need to calculate the gradient of the distance field and normalize the result. Does it mean that I just backtrack my particle till it is no longer "inside the object"? Then take average distance from surrounding, then take normalized average as "normal vector of the sourface"? Is that "all" I need to do? If such is the case, don't I need to render only "inside" of distance field? I don't need how close edges are when I am outside an object? Or do I need to know that as well? I really need clear step by step teaching material in which I can really look at it and read it through to understand. Are there any resource that teaches this technique?


Collision detection enhancement I am developping a spaceinvader like game. There comes the problem of how to handle collision detection. At first I was doing like that forEach(fireBall fireBalls) forEach(stormTrooper stormTroopers) if (collides(fireBall, stormTrooper)) Explode But then when playing I had the feeling the game was slowing down at some point, and I tought it had something to do with the multiple elements and the double loop. So I tried to break the loops whenever I had the chance, changing the forEach loops to for loops at the same time for (var i 0 i lt fireBalls.length i ) if (stormTroopers.length gt 0 amp amp fireBalls i .y gt stormTroopers 0 .y) break for (var j 0 j lt stormTroopers.length j ) if (fireBalls i .y gt (stormTroopers j .y 31)) break If the fireball isn't on the same "y" as any stormtrooper, the fireballs following are not going to be either, so no need to check. Same for the stormtroopers loop. This works only if the list is ordered, meaning the first stormTrooper of the list has the highest "y" value. The problem in my game is that all stormTroopers don't have the same speed, so I need to sort the list each time. This leads to my question in order to enhance the performance, I tried to break the loops, but for that I had to add a new operation sort the list of the stormTrooper. Is it worth it?


Continuous Collision Detection So I'm playing around with the separating axis theorem and collision. Obviously the problem of what face it collided with arose. I need the unit normal which is tangent to that face it collided with to resolve depth penetration. For rectangles it's easy. Update Y velocity If collision collision happened on the y axis. Update X velocity If collision collision happened on the x axis. But I wanted a more general that would work with all cases. I came up with two solutions 1.) So I thought about the solution above with a triangle. Obviously it wouldn't work because the rectangles faces are axis aligned and a triangles faces are not. So I figured I could just project the face and velocity using the dot product to solve it like the rectangle but for every face with its own axis. This would of course involve checking collision with the whole shape again for each face. 2.) I also figured I could do Polygon v Ray collision detection to figure out what face it collided with. My question is Which solution is faster? Or is there a better one that hasn't come to my mind? I don't know how to do Polygon v Ray collision but I would guess that foreach face, find intersection point between ray and segment of face.


Collision detection for sloping tiles I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out. First, some background. My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen). So, my 'slope tile' looks something like this Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think. Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile. I then multiply that by my slope (slope being height width or 100 102 in my case) I then divide by 2 to get the centre Finally, I subtract that result from the height of the tile (to invert it) This gives me the vertical center which I can compare with the centre of my sprite to check for collision. So, my code looks like this VertTileCentre Math.round(tileYCoord tile.quadHeight ((slope (spriteX tileX)) 2)) Results When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly. Edit 1 results from further experimenting I've noticed that the sprite when at the top left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up because it was hitting solid blocks behind (which have their own collision detection) Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) therefore if I remove the solid blocks, it works OK. So I have no idea why not dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!


How to handle collisions without ugly conditionals and type checking? (I asked a similar question, but this one is far more specific). How can I handle collisions without having to do a lot of type checking and if statements? People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision. I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if statements inside the handleCollision methods. For example (in psuedocode) class CollisionDetector foreach entity in entities foreach otherEntity in entities if(collision(entity,otherEntity)) entity.handleCollision(otherEntity) class Entity .. stuff omitted void abstract handleCollision() class Alien extends Entity .. stuff omitted void handleCollision(Entity entity) lots of ugly conditionals and type checking if(entity instanceof Missile) die() if(entity instanceof Alien) lifePoints ((Alien)entity).getDamagePoints() if(entity instanceof Wall) setVelocity(0,0) .. etc In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case. Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?


How should I learn about collision detection? If I want to use physics engine for my game then how should I go to learn collision detection algorithms? When I read AI book for games, the book talks about collision detection, so I want to learn it, but what kind of book would be best? If I had to choose to go and learn it what would you advise me to read? A physics book. (Game physics H.Ebrely) A real time collision detection book. (Same author) I don't know much about algorithms, some people say it's better to start with a physics book, because real time collision detection book depend heavily on algorithms.


Can't find out why aren't those collisions framerate independent I'm making a 2D Platform game and I'm having trouble with my collision detection. It doesn't seems to be framerate independent even though I used deltatime there. The problem is that at 60fps, a collision is sometimes detected too early whereas at 500fps there's no problem (so it really seems like this isn't framerate independent but I don't know why). Here's a video of the game running at 60fps https www.youtube.com watch?v P0hRJbw gcw And here's the code which is moving my character (I inspired myself about 2D Collision detection from the youtuber dermetfan) Makes the entity jump void Entity jump() m onGround false setVelocity(sf Vector2f(getVelocity().x, 500)) What to do at each frame void Entity update(sf Time dt) if (getVelocity().y gt 800) setVelocity(sf Vector2f(getVelocity().x, 800)) else setVelocity(sf Vector2f(getVelocity().x, getVelocity().y m map gt getGravity() dt.asSeconds())) checkCollisions(dt) Collision functions void Entity checkCollisions(sf Time dt) float oldX getPosition().x float oldY getPosition().y bool collX false bool collY false setPosition(getPosition().x getVelocity().x dt.asSeconds(), getPosition().y) Setting the position on x m collisionIncrement (getSize().x lt getMap().TILE SIZE) ? getSize().x 2 getMap().TILE SIZE 2 if (getVelocity().x lt 0) collX collidesLeft() Using collision tests else if (getVelocity().x gt 0) collX collidesRight() if (collX) Testing if there was a collision setPosition(oldX, getPosition().y) Correct position setVelocity(0, getVelocity().y dt.asSeconds()) setPosition(getPosition().x, getPosition().y getVelocity().y dt.asSeconds()) Setting the position on y m collisionIncrement (getSize().y lt getMap().TILE SIZE) ? getSize().y 2 getMap().TILE SIZE 2 if (getVelocity().y gt 0) collY collidesBottom() m onGround collY else if (getVelocity().y lt 0) collY collidesTop() if (collY) Testing if there was a collision setPosition(getPosition().x, oldY) setVelocity(getVelocity().x dt.asSeconds(), 0) bool Entity collidesRight() for (float step 0 step lt getSize().y step m collisionIncrement) if (getMap().isCollideable(getPosition().x getSize().x, getPosition().y step)) return true return false bool Entity collidesLeft() for (float step 0 step lt getSize().y step m collisionIncrement) if (getMap().isCollideable(getPosition().x, getPosition().y step)) return true return false bool Entity collidesTop() for (float step 0 step lt getSize().x step m collisionIncrement) if (getMap().isCollideable(getPosition().x step, getPosition().y)) return true return false bool Entity collidesBottom() for (float step 0 step lt getSize().x step m collisionIncrement) if (getMap().isCollideable(getPosition().x step, getPosition().y getSize().y)) return true return false


Collision detection with multiple polygons simultaneously I've written a collision system which detects resolves collisions between a rectangular player and a convex polygon world using the Separating Axis Theorem. This scheme works fine when the player is colliding with a single polygon, but when I try to create a level made up of combinations of these shapes, the player gets "stuck" between shapes when trying to move from one polygon to the other. The reason for this seems to be that collisions are detected after the player has been pushed through the shape by its movement or gravity. When the system resolves the collision, it resolves them in an order that doesn't make sense (for example, when the player is moving from one flat rectangle to another, gravity pushes them below the ground, but the collision with the left hand side of the second block is resolved before the collision with the top of the block, meaning the player is pushed back left before being pushed back up). Other similar posts have resolved this problem by having a strict rule on which axes to resolve first. For example, always resolve the collision on the y axis, then if the object is still colliding with things, resolve on the x axis. This solution only works in the case of a completely axis oriented box world, and doesn't solve the problem if the player is stuck moving along a series of angled shapes or sliding down a wall. Does any one have any ideas of how I could alter my collision system to prevent these situations from happening?


Collision within a poly For an html5 engine I'm making, for speed I'm using a path poly. I'm having trouble trying to find ways to get collision with the walls of the poly. To make it simple I just have a vector for the object and an array of vectors for the poly. I'm using Cartesian vectors and they're 2d. Say poly 550,0 , 169,523 , 444,323 , 444, 323 , 169, 523 , it's just a pentagon I generated. The object that will collide is object, object.pos is its position and object.vel is it's velocity. They're both 2d vectors too. I've had some success to get it to find a collision, but it's just black box code I ripped from a c example. It's very obscure inside and all it does though is return true false and doesn't return what vertices are collided or collision point, I'd really like to be able to understand this and make my own so I can have more meaningful collision. I'll tackle that later though. Again the question is just how does one find a collision to walls of a poly given you know the poly vertices and the object's position velocity? If more info is needed please let me know. And if all anyone can do is point me to the right direction that's great.


Combining Many Small Colliders into Larger Ones I am creating a game using a tile map made of many thousands of grid squares. At the moment, each square has a square collider on it for checking collisions. However, with many thousands of tiny blocks, checking them all for collisions is inefficient. If I had known the tilemap was going to look like this in advance, I could have just used 3 or 4 big colliders rather than thousands of tiny ones Is there some sort of standard algorithm for combining many small adjacent tiles into maximally large ones? If so, could someone describe it here, or point to literature on such algorithms? Alternatively, maybe pre processing the tile colliders in this way is completely the wrong approach. If so, what is the correct one to deal with the efficiency of an extremely large number of colliders?


Player won't move correctly due to gravity force pushing him into the ground I am making a tilemap platformer with pygame ad I defined the X and Y movement for the player and also a Y force that represents the gravity force to make it jump correctly. However, when my player falls off to the ground and the game begins, it doesn't move correctly neither to the right nor to the left direction due to the gravity force that keeps pushing him to the down. In addition to that, when the player jumps and i move it to the right, it's like it doesn't recognize the collision with the bottom rect of the wall (see gif below for a visual explanation of that). I tried disabling that gravity force when the player hits the ground and enable it when the player jumps but it didn't work as expected and I've got problems managing collisions (also, it doesn't make sense to disable gravity, right?) Here's a gif of the issue i'm facing with Here's my Player class class Player(pg.sprite.Sprite) def init(self, game, x, y) self.groups game.sprites pg.sprite.Sprite.init(self, self.groups) self.game game self.image pg.Surface((TILESIZE, TILESIZE)) self.image.fill(GREEN) self.rect self.image.get rect() self.move left self.move right False self.pos pg.math.Vector2(x, y) self.acc pg.math.Vector2(0, GRAVITY) self.vel pg.math.Vector2(0, 0) def jump(self) self.vel.y 3 def update(self) self.vel.x 0 if self.move left self.vel.x PLAYER SPEED if self.move right self.vel.x PLAYER SPEED self.vel self.acc self.pos self.vel self.rect.x self.pos.x TILESIZE self.rect.y self.pos.y TILESIZE if self.vel.y gt 0.5 self.vel.y 0.5 hits pg.sprite.spritecollide(self, self.game.walls, False) if hits if self.vel.x gt 0 self.pos self.vel self.rect.right hits 0 .rect.left self.vel.x 0 if self.vel.x lt 0 self.pos self.vel self.rect.left hits 0 .rect.right self.vel.x 0 hits pg.sprite.spritecollide(self, self.game.walls, False) if hits if self.vel.y gt 0 self.pos self.vel self.rect.bottom hits 0 .rect.top self.vel.y 0 if self.vel.y lt 0 self.pos self.vel self.rect.top hits 0 .rect.bottom self.vel.y 0


How can I determine which tiles in a tilemap an oriented bounding box (OBB) overlaps? I need to detect collisions between an oriented bounding box and a static tile map. My tile map class looks something like this function Tilemap(width, height, tiles) this.width width Width of the map in tiles this.height height Height of the map in tiles this.tiles tiles 1D array containing tiles, grouped by row Tilemap.prototype.getTile function (x, y) return this.tiles y this.width x Tilemap.prototype.setTile function (x, y, value) this.tiles y this.width x value My question is this How can I determine which tiles an OBB, represented as an array of vertices, overlaps? (I am writing in JavaScript but answers for any language would be appreciated.)


Bounding Volumes for Empty Space I'm creating an Android game that relies heavily on collision detection for a couple of players (at least up to 4). I researched hierarchical structures that could speed up the process. Because I have worked with hierarchies of axis aligned bounding boxes for ray tracing in uni, the sweep and prune algorithm is currently my favorite choice. However, I had the idea to use bounding boxes not only for the obstacles in a level, but also some boxes containing as much of the free space in the scene as possible. If the player's character stays within one of those during his movement between two frames no further intersection tests should be necessary. Could this approach reduce the number of intersection checks where a player's character intersects one or more axis aligned boxes but not the objects within? I highly doubt I am the first person who thought of this, yet I didn't find something like it online. So, is there a good reason not to do this? My best guess for why it isn't done is that there is no good rule to find applicable bounding boxes for empty spaces in between. But if they are precomputed before the game I don't see this as a problem. Maybe they could be bounding spheres instead. Those could be grown from an obstacle's surface until it touches obstacles in at least three points, like so Any advice would be greatly appreciated


Clip shadow frustum to scene bounds I have a global light in my scene. It casts shadows using shadow mapping and has an associated camera (for rendering to the shadow map). I'm going to refer to it as my "shadow camera" from now on. I need to find a way to place my shadow camera's near plane as close as possible to my scene's bounding box (clip it to the scene bounds). I need to do this so the shadow casters are never clipped by the shadow camera's near plane (otherwise I'd get holes inside of shadows) and to make sure I don't accidentally cull any shadow casters behind the camera. This would also allow me to increase the shadow mapping precision, because it lets me move the near and far planes closer together. Example 1 (possible to do using a simple plane check) Example 2 (NOT possible to do using a simple plane check) The black box is the scene's AABB (but it would be nice if this would work for OBBs or other shapes too). The yellow arrow represents the light direction. The green box is the shadow camera's frustum without any modifications. The red box is my desired result. At the moment I'm constructing the red box by projecting the black box onto the global light's direction vector and use the closest vertex's distance to compute the shadow camera's near plane. But this makes it impossible to get something as seen in the 2nd image. Instead the red box starts above the scene's AABB. I have thought of using SAT for this, but it doesn't seem to be the solution.


Is it possible to have concurrent collision detection where every entity acts at exactly the same time? There are many algorithms that can be used for collision detection. In many cases we check for an overlap in coordinates of an entity. If we make a triangle a,b and c. We have 2 entities at a and b heading for a collision at c but each of them are moving at exactly the same time, what kind of algorithm could work? It seems more like a chess game where you would have to predict every move that the other entity would have to make, if they swerve to the left to avoid a collision will they also run the chance to collide. Is it possible or is it too complex? Would it work for thousands and millions of entities in the same search space?


Exact collision time of two axis aligned bounding boxes I am trying to calculate the exact collision time of two axis aligned bounding boxes (aabb) as fast as possible (in the sense of CPU time). I have all the required information (aabb min, max, center, etc., velocity vector, and so on) My aabbs are not rotating, so they have linear velocity The aabbs can be both moving, only one of them might be moving, or they both might be steady My current approach creates lines from one of the boxes' corners and checks the collision among the planes of the other box (you can see the algorithm below) however it takes 6 times longer than I can afford. So, I am trying to find a faster algorithm however, I couldn't have managed, yet. My current quot slow quot algorithm Add velocity of Aaabb to Baabb and assume Aaabb is steady and Baabb is moving Calculate the corner positions of Baabb For each corner of Baabb, perform the line plane intersection with Aaabb's each 6 planes (I use the line intersection formulate (algebraic form) on Wikipedia) to check if there is an intersection. If a corner of Baabb intersects with a plane of Aaabb, verify the intersection point is behind the other 5 planes of Aaabb Keep the smallest value of d and return


Fast(er(est)) fullscreen scene collision detection technique ("selection buffer") My vertex format has a float4 Flags element used to pass miscellaneous data to shaders. Each mouse collidable object that is rendered has a unique ObjectID that is written to an ObjectID rendertarget which can be CPU sampled to index the hovered object. The remaining render targets are geometry lighting data. I've found this has advantages I set (Flags.x ObjectID) upon object creation so the vertex buffer only needs an initial upload and updates only when new ObjectID's (that will be rendered) are created. Everything else is per object instance. Essentially, "no" overhead added by using a Flags component for ObjectID. I'm semi certain that, since I have to render everything anyway, outputting one additional color to one additional rendertarget is already cheaper than ANY clever bounding container collision testing algorithm. Currently, I copy the entire ObjectID rendertarget back to the CPU, but even that could be further optimized. The depth buffer (that I'm using anyway) automatically ensures that the pixel I sample is the ObjectID of the top most, visible, mouse collidable, object. I don't have to check if the mouse position ray is within the bounds of anything, intersects with anything, visibilities, nothing. All of that is already sorted out by rendering the scene properly. Rendering the interface components first and reusing the ObjectID depth buffer to render the world, reduces the fill volume for the 3D scene drastically, if a lot of interface is visible. I've found only one disadvantage Since I render the interface first, if the camera has moved (the world hasn't been rendered yet), the WorldCoordinate available during Update() is incorrect. If the camera hasn't changed, the coordinate is correct. Immediately after rendering to the geometry buffers, but before any cursor dependent shaders are invoked, I update the CPU buffer and WorldCoordinate. The CPU buffer is only updated when necessary and, at most, once per frame. The "second sample" is during the following Update() and just re reads the (wrong if the camera has moved) value from the byte array. Still, no significant overhead and this is basically just a slight annoyance because I'm just debugging the value anyway. Currently, when the WorldCoordinate is usefully used (during render), it is correct. Overall, I've got pixel perfect, anything on the screen, mouse collision detection, with zero additional overhead beyond standard rendering. Minimal and or approximately fixed, regardless of screen scene complexity Why is this method not popular and or tutorialized? I assume most new ish games post process geometry buffers but I found nothing similar to this and just worked my way through the issues as they came up. To me, it appears as though I've got collision detection working for all of the objects classes that I haven't even written yet. All of the "tech" involved here is obvious and easy, so I feel like I must be missing something a future problem that I can't think of yet. Comments critiques of the "algorithm" are welcome. Best answers would point out critical flaw(s) and, for bonus points, work arounds. If this has been done before, is there an accepted best practice? Links to similars would be ok.


How can I reproduce the physics that we can see in Dawn of Titans? I'm working on a hobby RTS project and I want to implement collision physics between soldiers like in the mobile game Dawn of Titans. Here is a video reference https youtu.be Fnpot2NeJl8?t 341 How can I achieve this?


Collisions with complex assets from Blender in SceneKit I have a very basic workflow question I'm prototyping a game with Apple's SceneKit framework. It can automatically create a mesh for collision detection, but it will always be a convex hull. This works okay for simple meshes, but now I want my character wo walk into a house. The options I could come up with Use the same mesh for the physicsShape (could be too complex and a performance bottleneck) Build the level in SceneKit and only create atomic building blocks in Blender Create a second low poly version of the model and use that for collisions (basically twice the work? As you can see I have zero experience with game development and best practices. What is the typical way to do this?


Collision Detection point hitting a rotating rectangle Im developing a game which has a flying chopper and an enemy firing bullets at it. Whats the best way to detect when the bullet hits the bounds of the chopper. The chopper is placed to the left of screen, continously rotating around its center. Bullet is fired from the right, always in a straight line. Im using Marix post rotate and translate for the choppers rotation.To make it simpler, I just want to consider the chopper to be a rectangle. Lets say im not bothered about any more precision in terms of specific hit points.


Creating Complex Collision Shapes in GMS2 I'm pretty new to Game Maker Studio 2 and I've hit a wall in programming with their built in physics engine. I created a irregularly shaped object and I want to modify the collision shape so that it fits the shape of the sprite. In the built in collision shape editor it only allows you to create a convex shape with a max of 8 points. Is there another way to do this without having to plot out points individually in code? Thanks!


What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? Provided that both objects have rectangular hitboxes, x and y positions and height width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? No engine is being used.


Collision detection circle segment segment I've already implemented collision detection in my game loosely following this tutorial, which works great, but I realized there's one major flaw. The player and the enemies are circles, while the obstacles can be either segments or polygons or circles. Now, let's say I have segment A from point (100, 100) to point (300, 100) and segment B from point (100, 200) to point (300, 100), which means they form an acute angle, and player has it center in point (100, 125), with a radius of 25. If player starts moving right, it will eventually collide against segment B. My method checkCollisions() will return a vector, but if I apply that vector on player, it will be moved up and left, and will overlap segment A. If I call checkCollisions() a second time, player will be pushed down and collide again with segment B, so recursive invocations aren't a solution. Any ideas? Here's a picture to explain The g n vector direction is along the bisector of the two little vectors, but how do I find the length?


2d Tile Based Collision Response Right now I am trying to make a 2d collision response system for a platformer, and the algorithm I have for it works quite well. The only problem is that if the player is standing exactly on a tile, he cannot move. I think this is related to the fact that the manager is checking if he is colliding on the X axis, instead of the Y Axis. I have thought of making one big AABB for a check, using all applicable tiles, but I feel as if there is a simpler way. I don't really understand normals, so I have not tried anything with them yet. Right now, I am getting the centers of both objects, the distance inbetween them, and the minimum distance between them, returning the overlap. And then applying the overlap to the players position. It looks like this sf Vector2f centerA( AABBFirst.left (AABBFirst.width 2), AABBFirst.top (AABBFirst.height 2)) sf Vector2f centerB( AABBSecond.left (AABBSecond.width 2), AABBSecond.top (AABBSecond.height 2)) sf Vector2f distance(centerA.x centerB.x, centerA.y centerB.y) sf Vector2f minDistance( (AABBFirst.width 2) (AABBSecond.width 2), (AABBFirst.height 2) (AABBSecond.height 2)) return sf Vector2f( distance.x gt 0 ? minDistance.x distance.x minDistance.x distance.x, distance.y gt 0 ? minDistance.y distance.y minDistance.y distance.y) I apologize if this question has already been asked and answered before, I have not found the proper terms to search for.


Is there a specific library to handle the collision system of a big game world like WoW, or any physics library will work? Nothing else to add. Is there a specific library to handle the collision system of a big game world like WoW, or any physics library like ODE will work?


Making the ball go faster makes collision detection impossible I have a simple tennis game like Breakout. I have a ball, and a racquet made from a long rectangle. The ball bounces around the walls, and the game terminates when the ball hits the floor. To prevent this, I have a long racquet I can move horizontally that the ball can hit. Each time the ball hits the racquet, the speed of the ball increases. The speed increases by adding to the number of pixels for each increment of the ball. This means that after a while (around 50 hits), the steps of the ball become quite long. The ball moves at 50 px per frame. With long steps, the ball might just jump over the racquet, and not detect collision. To prevent this, I was thinking of incrementing the FPS, instead, and keeping the ball speed fixed. This would probably work, but I don't think changing the FPS is the right solution. How should I go about solving collision detection at higher speeds?


Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles


2D physics collision gravity problem? I'm using Love2D and my own physics engine to create a 2D platformer. Y collision works fine, but X collision... well, it's a bit buggy. When I move off of a small platform I've created, I fall but it is a lot slower than what my gravity is set to. Here's my code for collision function world.collisionCheck(o) for k, v in pairs(world.objects) do if v o then if v.Type "Rectangle" and o.Type "Rectangle" then if o.Position.Y (o.Size.Y 2) gt v.Position.Y (v.Size.Y 2) then o.Velocity.Y 0 o.onGround true end if not (o.Position.X (o.Size.X 2) gt v.Position.X and o.Position.X (o.Size.X 2) lt v.Position.X (v.Size.X)) then o.onGround false end right left end end end end As you can see, it's pretty bad. The code for the actual physics (gravity, movement, etc.) is a bit better function world.update(t) for k, v in pairs(world.objects) do if v.Static true then v.Position.X v.Position.X v.Velocity.X if v.onGround false then if v.Velocity.Y lt world.Gravity then v.Velocity.Y v.Velocity.Y world.Gravity t end end v.Position.X v.Position.X v.Velocity.X world.Meter v.Position.Y v.Position.Y v.Velocity.Y world.Meter v.Velocity.X v.Velocity.X world.Friction world.collisionCheck(v) end end end However, it could still use some work. Whenever I step off of a 150 pixel by 15 pixel platform, I fall a lot slower than 9.8 meters per second. My meters are set to two pixels, and I'm falling at about a meter per second, which is much slower than the expected 20 pixels per second I get while still on the platform. Everything I've tried doesn't seem to fix it there's no problem in the movement code, and nothing I change in the collision code seems to fix it. Is there some silly problem I've overlooked? EDIT Okay, so I implemented a small fix which somewhat solves my problem. I modified the collision code so that it checks if it is below what is being tested for collision, and it seems to accelerate as normal when the top of the object is below the object being collided with, and vice versa. Am I correct in assuming I just need to add something to detect if the x value is in the correct range, too?


Play an effect where a sprite touches a trigger I have a sprite based GameObject in Unity to which is attached a RigidBody and a Collider2D. When this GameObject comes into contact with a particular Collider2D Trigger, I want a particle effect to play at the point of contact. This sounds extremely simple to set up and yet I can't seem to find any solution that works, since OnTriggerEnter2D doesn't bother to provide hit coordinates. Please note that the trigger represents a non solid space, so adding a solid (non trigger) collider for hit detection is not a solution. The sprite is large, so I can't just play the particle effect at its transform position. Raycast is not an appropriate solution for this problem it doesn't handle nearly enough cases.


How to design Client server hybrid hit detection with projectile weapons? Hybrid hit detection here refers to a architecture where client sends a hit claim to server and server verifies it with a tolerable error limit to confirm the hit or deny it. This technique may work well with hit scan or instant hit weapons because you only have to check it for one frame tick. But in case its a physics projectile I.e where an actual projectile flies to the target like a real bullet, the hit is the result of flight over more than one frames and varying physics state. As such verifying the hit could be very cumbersome and resource intensive. So how would one go for server client hybrid approach in this scenario?


Voxel terrain collision detection with AABBs I'm working on implementing collision detection on voxel terrain (Like Minecraft) with AABBS. Right now, I have it so I can tell if a point is within a voxel or not, I do this by having a 2D byte array of active voxels. If a byte at any index is 0, the voxel is air. If its 1, its solid. Right now I'm just testing to see if the voxel at the player's position vector is solid or not. My problem is, I now wish to implement AABBs to get more precise detection, but I have no idea how to do it without checking if all the voxels within the AABB are solid. That might now be a problem for games like Minecraft, where there would only have to be about 1 extra voxel check, but the voxels in my game are much smaller (The player's dimensions are about 4x10x4), so I would have to check a lot of voxels. Ive seen one or two other people having a issue similar, but I didn't find the answers they got clear enough, and so I come here asking for your help. Thanks.


OBB vs OBB Collision Detection Say you have two Bounding Box Objects each of them storing the current vertices of the box in a vector with all the vertices of the object rotated and translated relative to a common axis. Here is an image to illustrate my problem How can I work out if the two OBB's are overlapping any links to help explain the solution to the problem would be welcome. Nothing too convoluted please...


What is the fastest way to work out 2D bounding box intersection? Assume that each Box object has the properties x, y, width, height and have their origin at their center, and that neither the objects nor the bounding boxes rotate.


How to represent a game character in code? In a previous game I wrote I had a game character class. This class tracked the location, velocity, and a set of states. Except the states were tied very close to the animation. Each state would have a list of buttons that can transition it other states, and an animation that would go with that state (you could also do per frame animation state changes, if you wanted to do something like have a very specifically timed punch or something). All of the collision data for the character was done on a per animation frame basis. This was done for a fighting game, so it seemed necessary at the time to have the animation and collision tied so closely to the character state. But the programmer in me feels like this is mixing responsibilities. And now I'm making a game engine that I want to be a little bit more generic than that. How do you typically organize the structures relating to the characters, how they're drawn, how they interact with each other and the world, etc? I realize this is sort of a vague question that depends on the type of game I want to make, but I think seeing how other people handle this would be useful. (and if it matters, this is all for a 2D game.)


Updating physics for animated models For a new game we have do set up a scene with a minimum of 30 bone animated models.(shooter) The problem is that the update process for the animated models takes too long. Thats what I do Each character has 30 bones and for every update tick the animation gets calculated and every bone fires a event with the new matrix. The physics receives the event with the new matrix and updates the collision shape for that bone. The time that it takes to build the animation isn't that bad (0.2ms for 30 Bones 6ms for 30 models). But the main problem is that the physic engine (Bullet) uses a diffrent matrix for transformation and so its necessary to convert it. Code for matrix conversion ( 0.005ms) btTransform CLEAR PHYSICS API Mat to btTransform( Mat mat ) btMatrix3x3 bulletRotation btVector3 bulletPosition XMFLOAT4X4 matData mat.GetStorage() copy rotation matrix for ( int row 0 row lt 3 row ) for ( int column 0 column lt 3 column ) bulletRotation row column matData.m column row for ( int column 0 column lt 3 column ) bulletPosition column matData.m 3 column return btTransform( bulletRotation, bulletPosition ) The function for updating the transform(Physic) void CLEAR PHYSICS API BulletPhysics VKinematicMove(Mat mat, ActorId aid) if ( btRigidBody const body FindActorBody( aid ) ) btTransform tmp Mat to btTransform( mat ) body gt setWorldTransform( tmp ) The real problem is the function FindActorBody(id) ActorIDToBulletActorMap const iterator found m actorBodies.find( id ) if ( found ! m actorBodies.end() ) return found gt second All physic actors are stored in m actorBodies and thats why the updating process takes to long. But I have no idea how I could avoid this. Friendly greedings, Mathias


How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?


Detecting collision between a sprite and many tiles I have been looking at the following question Tile coordinates and am thinking of using this for collision detection in my tile game. The set up in my game is similar to this, in that there is a grid of tiles, and the sprite will move to (x,y) coordinates. However, if I were to have an object such as a box in my world that is made from multiple tiles, how would I get the collision detection to work? Any ideas welcome.


3D collision for non mathematician I am having an extremely hard time understanding smooth 3D collision. I have spent a month trying to figure out the math and still cannot get perfect collision detection that perform the same way as in games such as Quake. I've resorted to a virtual 2D rectangle collision model applied to 3D plane, but it's full of bugs and doesn't handle slopes. It seems that very complex math is required like matrices and vectors. There are lots of tutorials online but they are full of mathematical symbols and it's impossible for a math novice like me to understand it, I also don't have time to go through a mathematics basics from the beginning. Is it possible to do collision without vectors or matrices or a guide somewhere that can explain in non mathematical terms how to implement smooth collision? How can a nonmathematician overcome 3D math?


Gravity and collision detection interfering with player movement I am attempting to implement collision detection for a 2d sidescroller game and I'm having trouble keeping gravity from interfering with player movement. Every frame I get and handle input, creating values for a point that represents the players movement vector. I then add gravity to the vector and check for collisions. This is the way AI will be handled as well. The problem I'm having is when the player is on a floor tile, even if the input says to walk horizontally, after I add gravity to the move vector, collision detection returns a collision so the movement is completely negated. I know i can test which a is is the problem, negate that and move the player but then if I change the players movement vector inside collision testing, wouldn't I have to cull for collisions again based off the new move vector? I don't know if this has to do with input handling or collision testing. So how should I go about adding gravity to the players movement?


Unit collision avoidance for RTS I'm developing an RTS, and having a little difficulty with collision detection. From what I understand RTS generally don't bother with collision detection and just try to avoid collision, and that is what I am trying to accomplish. My game uses a grid for static obstacles, but units are not bound to the grid for movement. How do I allow for units to avoid collisions, both with static obstacles and with other units? Right now my workaround is to redirect units around static obstacles every time they move from point to point (and every time a new obstruction is placed on map, units replan their routes). This doesn't seem like an ideal solution, but it works. I have no idea how to handle unit unit collisions.


How to detect collisions in AS3? I'm trying to make a simple game, when the ball falls into certain block, you win. Mechanics The ball falls through several obstacles, in the end there are two blocks, if the ball touches the left block you win, the next level will contain more blocks and less space between them. Test the movie (click on the screen to drop the ball) http gabrielmeono.com downloads Lucky Hit Alpha.swf These are the main variables var winBox QuickObject You win var looseBox QuickObject You loose var gameBall QuickObject Ball dropped Question How do I trigger a collision function if the ball hits the winBox? (Win message Next level) Thanks, here is the full code package import flash.display.MovieClip import com.actionsnippet.qbox. import flash.events.MouseEvent SWF(width 600, height 600, frameRate 60) public class LuckyHit extends MovieClip public var sim QuickBox2D var winBox QuickObject var looseBox QuickObject var gameBall QuickObject Constructor public function LuckyHit() sim new QuickBox2D(this) sim.createStageWalls() winBox sim.addBox( x 5,y 600 30, width 300 30, height 10 30, density 0 ) looseBox sim.addBox( x 15,y 600 30, width 300 30, height 10 30, density 0 ) make obstacles for (var i int 0 i lt (stage.stageWidth 50) i ) End sim.addCircle( x 1 i 1.5, y 16, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 15, radius 0.1, density 0 ) Mid End sim.addCircle( x 0 i 2, y 14, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 13, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 12, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 11, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 10, radius 0.1, density 0 ) Middle Start sim.addCircle( x 0 i 1.5, y 09, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 08, radius 0.1, density 0 ) sim.addCircle( x 0 i 1.5, y 07, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 06, radius 0.1, density 0 ) sim.start() stage.addEventListener(MouseEvent.CLICK, clicked) .. param e MouseEvent.CLICK private function clicked(e MouseEvent) gameBall sim.addCircle( x (mouseX 30), y (1), radius 0.25, density 5 )


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


Bounding volume hierarchy linked nodes (linear model) The scenario A chain of points (Pi)i 0,N where Pi is linked to its direct neighbours (Pi 1 and Pi 1). The goal perform efficient collision detection between any two, non adjacent links (PiPi 1) vs. (PjPj 1). The question it's highly recommended in all works treating this subject of collision detection to use a broad phase and to implement it via a bounding volume hierarchy. For a chain made out of Pi nodes, it can look like this I imagine the big blue sphere to contain all links, the green half of them, the reds a quarter and so on (the picture is not accurate, but it's there to help understand the question). What I do not understand is How can such a hierarchy speed up computations between segments collision pairs if one has to update it for a deformable linear object such as a chain wire etc. each frame? More clearly, what is the actual principle of collision detection broad phases in this particular case how can it work when the actual computation of bounding spheres is in itself a time consuming task and has to be done (since the geometry changes) in each frame update? I think I am missing a key point if we look at the picture where the chain is in a spiral pose, we see that most spheres are already contained within half of others or do intersect them.. it's odd if this is the way it should work.


Libgdx how to store every single point drawn using touchdragged? Basically i am trying to detect line collision. The problem is when intersection occurs quickly(touch dragged is done quickly like fling), the collision is not detected. It seems as if 'touch dragged' doesn't store all points.


Without using a pre built physics engine, how can I implement 3D collision detection from scratch? I want to tackle some basic 3D collision detection and was wondering how engines handle this and give you a pretty interface and make it so easy... I want to do it all myself, however. 2D collision detection is extremely simple and can be done multiple ways that even beginner programmers could think up When the pixels touch when a rectangle range is exceeded when a pixel object is detected near another one in a pixel based rendering engine. But 3D is different with one dimension, but complex in many more so... what are the general, basic understanding examples on how 3D collision detection can be implemented? Think two shaded, OpenGL cubes that are moved next to each other with a simple OpenGL rendering context and keyboard events.


Changing speed of an object Is there a way of changing speed of an object at certain time? I want to change my speed to my initial speed after colliding with any object. I have already added bounce Physics to my colliding objects and player object with Friction set to 0. Please help.


How does the SAT collision detection algorithm work There are a lot of tutorials and sample code available showing how to implement the SAT collision detection algorithm. But can someone explain, without math or code, what are the general principls behind this technique.


Meaning of offset in pygame Mask.overlap methods I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges. It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall. Here is the conceptual image it I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand. Here are the docs for the method Mask.overlap Returns the point of intersection if the masks overlap with the given offset or None if it does not overlap. Mask.overlap(othermask, offset) gt x,y The overlap tests uses the following offsets (which may be negative) .. A yoffset .. B xoffset


Box2D Efficient method to create b2Chainshapes for a tile based map? I'm working on a platforming game with tile based levels. I store the collision model for my tileset in an array. This is how the collision model for a 4x4 tilesheet would look like (I can't post pictures yet so this link will have to suffice Tileset example). The red dots are the vertices of the b2ChainShape. When I load a level, I look up the collision model for each tile and create a b2Body at the corresponding place. The problem is that between the tiles, my character can experience a "bump" because it gets stuck on the edge of the shape of the next tile's body. Is there an existing algorithm to connect the bodies of neighbouring tiles to a single b2ChainShape? Or should I ditch the idea of tile based collision models all together and simply create the collision model for the whole map with the Tiled map editor? I don't create the the collision map with the Tiled map editor at the moment, because it is very time consuming for slopes and hills.


Unity mesh collider detecting collision on object empty inside I'm trying to get my first 3D game done with Unity. In this game the character will be flying through some rings. I made the ring asset with MagicaVoxel, exported it in .obj and reimported in Unity withouth problems. I've set a rigidbody and a box collider on the character model and a mesh collider withouth rigidbody to the ring and I've also set Convex and added the default mesh of the ring. The problem is that whenever I try to go inside the ring, I can't because I collide even with the empty part inside it. I'm not sure on how to made Unity collide only with the external part, but as far as I can see in the editor I'm using, I've no setting for it. I'm using Unity 5.3.4f1. Can someone please explain me how to solve this problem? Thank you very much. EDIT I'm sorry, I forgot to mention that I'm aware I can unset the ring mesh Convex property and get it to work. The problem of this solution, though, is that whenever I put adjacent rings I can glitch through them even if there's no space to fit. So basically I need a solid collider with Convex only on the external part of the ring and with empty space to fly through on the inside. Is this possible somehow?


What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? Provided that both objects have rectangular hitboxes, x and y positions and height width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? No engine is being used.


How to do one way collision? I would like to know how can I do one way collision. It's the collision common in mario's games and many platforms. I try to do an code but I cannot post because it's part of a paid game. Basically I have two rectangles like this struct Rect int x, y positions in the world int w, h width and height The rect A moves and the rect B is fixed with the world. Someone has a idea of how to do this?


OnTriggerEnter OnTriggerStay triggers multiple times and is not been call a second time I am working on a feature that when the Player pass thru a door, a message will popup on the screen. I'm having few problems Debug.Log gives me from 2 to 6 logs when I pass thru the collider plane and when I come back to the same collider plane the script it is not been call a second time. What I'm trying to achive is that Debug.Log gives me only one log and every time I pass thru the collider the script runs again. so here is my code function OnTriggerEnter (other Collider) OnTriggerStay gives the same result if (other.tag "Player") isColliding true else isColliding false function OnGUI() if (isColliding) Debug.Log(isColliding) Application.ExternalCall('hive.OpenHiveAlert', 'test') function OnTriggerExit() Destroy(this) Any help would be appreciated, thanks.


Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles


How client movement prediction syncs with server position to avoid a clip around collision? I have searched a lot on stackexchange and on google, yet I have not found a satisfactory answer to this seemingly simple question. I am making an online multiplayer game where the players navigate a 2d map with basic square obstacles. In this case I am making collision checks both on the client and the server, where the server broadcast everyone's position once per second as authority. However, when making a sharp turn around a square, often times either the client makes the turn while the server clips, or the client clips at the corner while the server makes the turn. That is understandable considering the possible discrepancy between the position on the server and the predictive position of the client. How do online multiplayer games usually work around this simple yet crucial problem? I understand that it comes down to a pixel perfect sync which isn't possible, but how do other games navigate around this issue, to give a flawless collision experience? What I am considering of doing Increase the position broadcasting rate from 1 time per second to however high needed to accurately sync the positions (20 sec). I believe this is the solution most games are doing. This however, will drastically increases the load on the server. In my case, the game's main mechanism isn't the navigation (think MMO), so I am leaning towards only checking collision on the client side, and have a simpler collision check on the server to ban walk through wall hackers. This would relax the server from heavy collision operations which is nice too.


How do I detect collisions between a particle based net and a ball? I've implemented a net using Verlet integration and many points connected with constrains like this demo, but in 3D. I want to implement collision detection between this net and a ball (like in a soccer game), so the net catches the ball. I've tried checking for collisions between the ball and net points (treating each like a small sphere), and this somewhat affects the net, but the ball passes through the gaps between points easily. How should I be approaching this?


Lerping character moving up and down slope tiles So, when interpolating position against a standard 'horizontal' platform, everything works great. What happens is something like this..... (Question continues after graphic) Now, the question I have is, how do we correctly interpolate the player's sprite (blue circle) against a 45 tile? When I attempt to do this, what happens, is that when the player is going up the slope, it is slightly embedded in the tile and when coming down the slope, it floats slightly above the tile. In the example above, the sprite effectively 'stops' moving along the Y Axis, so therefore, interpolation along that axis stops, however when interpolating the position against a slope, the sprite moves in an X and Y direction, so never stops. I think this is causing the issue, if my logic is correct, some more graphics follow to illustrate what I mean.... What am I doing wrong? How do I interpolate my sprite while making sure it's 'on' the slope at all times? For moving up a slope When moving down slope Summary When interpolating against a horizontal platform, although the sprite isn't rendered on the platform in the frame straight after collision has been resolved, it is rendered on the platform during subsequent frames because the difference between the old and new positions has become 0 as it is no longer moving. However against a slope, again, the initial frame is incorrect but then the sprite moves again, so the next frame is also wrong etc so it never 'settles'. Note it does move at the slope's angle just not on the slope. I'm trying to work out how to get my two points along the 45 slope and interpolate between them (ie, along the slope)....


Simple (and fast) dices physics I'm programming a throw of 5 dices in Actionscript 3 AwayPhysics (BulletPhysics port). I had a lot of fun tweaking frictions, masses etc. and in the end I found best results with more physics ticks per frame. Currently I use 10 ticks per frame (1 60 s) and it's OK, though I see a difference in plus for 20 ticks. Even though it's only 5 cubes (dices) in a box (or a floor with 3 walls really) I can't simulate 20 ticks in a frame and keep FPS at 60 on a medium aged PC. That's why I decided to precompute frames for animation, finishing it in around 1700 ticks in 2 seconds. The flash player is freezed for these 2 seconds, and I'm afraid that this result will be more of a 5 seconds or even more, if I'll simulate multi threading and compute frames in background of some other heavy processes and CPU drawing (dices is only a part of this game). Because I want both players to see dices roll in same way, I can't compute physics when having free resources, and build a buffer for at least one throw of each type (where type is number of dices thrown). I'm afraid players will see a "preparing dices........." message too often and for too long. I think the only solution to this problem is replacing PhysicsEngine with something simpler, or creating own physicsEngine. Do You have any formulas for cube cube and cube wall collision detection, and for calculating how their angular and linear velocities should change after a collision occurs? Edit I'm assuming the only way to solve my problem is to make a cube cube and cube wall collision engine, however maybe there's another solution for my problem. As Arthur pointer out, there can be one animation for me this is just a shortcut, I could as well show the final result without any dices rolling. However, I thought about making 100 precomputed dice throws, though a user won't avoid repetition here as well. Sometimes a dice sits on it's edge (or corner) for a while, and that gives player some excitement (will it fall on 5 and give me a full house?), but with limited number of animations a player would already know how the animation will end. Buffering solution would work, if players would see dices roll in different way (results would still be the same) I'm considering this solution, however I'm still going to try to create a simple physics engine and see how it works. less ticks is a solution I don't consider, because at as few ticks to be able to simulate physics in real time, the dices behave not better than if I treated them as balls in my physics engine...


How will the velocities of two moving objects change once they collide? I'm making a small game where things can fly around and collide. Things like boxes and so on. For each object, I have an array of all forces acting upon it, I have it's mass, it's position and it's velocity in both directions (a 2D vector). I know how to detect collision between them, but I just don't know how to react. I used to calculate their orientation towards each other, it they were on top one another, I would just negate their y speed (v.y v.y), and if they were next to each other on the x axis I would negate their x speed (v.x v.x). Now, this isn't very realistic, so, how do I do it? All objects are rectangles represented by x, y, w, h vectors. Objects can't rotate.


How do I find the intersection of a ray and a cylinder? I'm looking for the algorithm to find the intersection (or lack of) between a ray and a cylinder. I have rotating coin like objects in my game world and need to check for a collision on that object. I also need to know the location of intersection to determine which part of the coin was hit. The cylinder has an arbitrary rotation. I can provide as input the direction (vector) it is facing, a centre point, and a radius. For the ray I can generalize to a line, as it'll be easy to check within the segment afterwards. Ideally I'd like the array to be an infinite cylinder, but I can easily fudge this aspect once I have the collision for a line.


How to retrieve vertex information from ID3DXMesh I need to know the position of each vertex (and triangles) from a mesh (a pointer to ID3DXMesh, created by calling functions like D3DXCreateBox, D3DXCreateTeapot and D3DXCreateSphere) to perform some collision detection. I've tried using GetVertexBuffer() and GetIndexBuffer() but I don't know how to use the structures to retrieve point data in the world coordinate system. How can I achieve that?


How can I implement rectangle collision response? I am working on a game in JavaScript and my current implementation of collision uses the shortest distance to push the intersecting object away, which isn't always correct. I've made this diagram of the ideal collision. The red box represents the starting position, the green box represents the proper position and the black box represents the static object it is colliding against. The blue arrow is the velocity vector. With my current implementation, the object would be placed in its final position and pushed out (and in this case it would be pushed left) How can I fix this?


Whats an elegant implementation for 2D collision detection in a block based game? to make things clear, i do not want to know HOW to implement collision detection mathematically. What i am looking for is an elegant way to check for collisions without having to manage seperate lists of objects, maybe for example implementing a ICollidable interface. currently i have a simple gameloop while(runGame) handleInput() update() render() So there are two possibilities which come straight to my mind. First, ill add an extra call to a method or class handling collisions. while(runGame) handleInput() update() checkCollisions() render() Second, every gameobject gets a list of nearby other objects in its update method. so it can do the collision on its own while(runGame) handleInput() update(otherNearShapes) render() i dont like both of these for two reasons. in the first, i have to manage a seperate list of objects which implement an ICollidable interface. in the second, the update method handles more logic than it should in my opinion. so, is there an elegant way of integrating collision detection in my game (loop)? searching the net always only results in how to calculate stuff, but thats not what i want to know.


My sprites do not always respect collisions in Pygame I have a Player sprite (40x40 pixels) and Tiles (20x20 pixels) which build the terrain. At the 4 edges there are 2 rows or columns (depends on vertical or horizontal) of wall tiles. Those are the limits which the player should not be able to overpass and collisions player wall are checked there. Most of times, it recognizes collisions, but sometimes it doesn't. When I move the player until the map limit and it hits the wall tile, it stops, but sometimes if I continue trying to move it against the wall, it doesn't respect the collision and enters in the wall. At this point, once the player enters in the wall tile it can only moves over wall tiles... So, am I doing something wrong or is it just a pygame collisions bug? Here is the method to check collisions def checkCollision(self) from prueba import limitGroup listLimits limitGroup.sprites() for i in range (0, len(listLimits)) if listLimits i .kind "wall" and self.rect.colliderect(listLimits i ) return True return False And here is the update() method to move the player. def update(self) for event in pygame.event.get() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load("bullet.png"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY)) key pygame.key.get pressed() if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10


MMO Collision detection I am building a MMO game server for a 2D game and am currently implementing the collision detection, and I am would like to know what I should do. Lets say I have 1000 players playing and 10,000 objects, should I just iterate over them all to determine if colliding? This seems a bit pricey. I could separating the world into chunks and iterating every object for each player in it's chunk. I would like to know some other ideas or what is standard. What's the best way for a MMO server to handle collision detection with static objects?


Should particles check if they are in a region, or regions if particles are in them? I have around 100 to 200 particles in my game. Then I have 5 to 20 regions (circle shape) which should count the particles which enter them and add some force to them, so they change their direction. My idea was now to keep a list of all particles and every region should check the whole list every frame, whether a particle is inside it. For this I calculate the distance between the particle and the central point of the region and check weather its lt the radius of the region. Is this the most efficient way to do it? Or should every particle have a list of all regions and check whether they are in one of it? Or a totally different approach? I would like this application to be able to run also on older mobile devices like an iPhone 4S.


Have the character automatically slide around obstacle corners Like this The player is only holding right, however the character still moves up a bit to go around an obstacle. My current collision system has access to The entity's previous position The entity's current position The entity's (axis aligned) bounding box All the obstacles and their (also axis aligned) bounding boxes Also it proccesses each axis separatelly. How can I implement this?


Can you help with collision detection and response in a 3D car racing game? I am trying to implement the collision detection and response in 3D car racing game. I have a car model, for collision I am assuming my car as a cuboid. my collision detection with walls is quite good and the response is also good. My model has a velocity, position, acceleration and orientation. I am using matrix to save the orientation and position. My problem is collision and its response with the ground (in my case it's road). When the ground is a simple plane with a constant y axis, then there is no need for collision detection as there is no force or movement in the y direction. But if my road is not linear, if it has some elevation, then I am having a collision detection problem when it comes to calculating its orientation. Any help and suggestions will be of great help.


Collision detection between draggable object and world objects? I have a game I'm making in Javascript that will involve combining items by dragging and dropping them onto each other. Think Alchemy or similar. So far, so good, but I hit a snag while trying to figure out how I can detect collisions between the two entities! I have a (really) basic bounding box test function isColliding(a, b) if (a.x a.width lt b.x a.x gt b.x b.width a.y a.height lt b.y a.y gt b.y b.height) return false else return true The trouble I'm having is that in practice, this is fine for detecting the mouse colliding with an object to pick it up, but I'm stuck on how I can, after I've grabbed an object, test to see if that object I have grabbed is colliding with any of the multiple other objects that exist in the window. I tried doing Core.objectCollision function() if (Core.Mouse.isHolding ! null) for (i in Core.Objects) if (isColliding(Core.Mouse.isHolding, Core.Objects i )) console.log("Colliding with world object!") This function is inside my update loop, but of course the object I'm holding is within my Core.Objects array too, so technically collides with itself. I really think I'm missing something obvious, but a lot of my searches for help have been returning how to simply detect collision between two already known items, however I need it so any item I grab can be tested against any other item in the view. Please also note I'm trying to avoid libraries for the time being, I'd rather learn the functionality myself. Thanks for any help!


How to handle interactions between a sprite (player) and another sprite? What's the proper way, a proper way, or any proper way at all, to handle interactions between a sprite (usually a player) and another sprite (can be any other object)? (in a tile based world) i.e. getting into a vehicle, talking with other character, reading signs, etc. My first instinct is to have some kind of "feeler" or interaction rectangle that's always in front of the player in the direction the player is facing. Then if that rectangle overlaps some kind of intractable object (driver door on vehicle, other character, sign, etc) I would be able to initiate an interaction. Is this a naive implementation? EDIT This is for a 2D engine, written in C for Xbox Live Arcade and Windows.


Libgdx collision detection and response I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the Rectangle.overlaps method. In response I am trying to find out at what edge the player hits the tile and then react accordingly. Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile). I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since Rectangle.overlaps() is used I am only reacting to a collision already happening. Here the source private void resolveCollision() setUpPlayerRec(allObjects.get(0)) for (Rectangle r2 tiles) if (!playerRec.overlaps(r2)) continue else onCollisionWithTile(r2) private void onCollisionWithTile(Rectangle r2) Gdx.app.log("Collision Detected", "Player collided with tile") float diff if (playerRec.x playerRec.width lt r2.x) LEFT EDGE OF TILE controlledPlayer.getPosition().x (r2.x playerRec.width) controlledPlayer.getVelocity().x 0 else if (playerRec.x gt r2.x r2.width) RIGHT EDGE OF TILE controlledPlayer.getPosition().x (r2.x r2.width) controlledPlayer.getVelocity().x 0 if (playerRec.y lt r2.y) HIT TOP OF TILE diff (playerRec.y playerRec.height) r2.y controlledPlayer.getPosition().y Math.abs(diff) jumptime MAXJUMP controlledPlayer.setJumpState(JUMP STATE.GROUNDED) else if (playerRec.y lt r2.y r2.height) HIT BOTTOM OF TILE controlledPlayer.setJumpState(JUMP STATE.GROUNDED) jumptime 0 diff playerRec.y (r2.y r2.height) controlledPlayer.getPosition().y r2.y r2.height


Why does the player fall down when in between platforms? Tile based platformer I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER FRAME event. It's only for collision from the bottom for now. var i int var j int var platform Platform var playerX int player.x 20 var playerY int player.y 20 var xLoopStart int (player.x player.width) 20 var yLoopStart int (player.y player.height) 20 var xLoopEnd int (player.x player.width) 20 var yLoopEnd int (player.y player.height) 20 var vy Number player.vy 20 var hitDirection String for(i yLoopStart i lt yLoopEnd i ) for(j xLoopStart j lt xLoopStart j ) if(platforms i 36 j ! null amp amp platforms i 36 j ! 0) platform platforms i 36 j if(player.hitTestObject(platform) amp amp i gt playerY) hitDirection "bottom" This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.


How to do collision detection on marching cubes terrain? I'm writing the physics part of my game engine. The world uses the marching cubes algorithm on a 3d perlin noise to make the terrain. How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible. What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron. EDIT The terrain is not "cubed" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video) https www.youtube.com watch?v 4rA3fdKWQA I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver. Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world.


Looking for collision detection algorithms for broad and narrow phases between non convex polyhedrons I have some experiences on particle system simulation (namely DEM Discrete element method), in which an individual particle with realistic shape (convex and non convex) is approximated by gluing 3D spheres together (non overlapping or overlapping), and act like rigid body. The collision detection is performed by the simplest sphere sphere contact. Nevertheless, for particle shape representing by polyhedrons, almost all the collision detection algorithms for broad and narrow phases are based on convex polyhedron (e.g. GJK). For non convex concave shapes, convex decomposition is required to divide the concave object into many convex components (e.g. V HACD). At this point, I really want to know the details on 1) how to store the concave objects via many convex components into memory (like BSP tree?) 2) collision detection and contact forces calculation between convex concave, concave concave objects. I have searched quite a few relevant books like "Real time collision detection" and "3D game engine design", etc, unfortunately I haven't find any details on this topic yet. Could some veteran game developers give some advice or insight on how to implement collision between concave objects? Cheers, David Update 1 Seems the physics engines likes Bullet3 and reactPhysics3D are able to simulate collision of non convex objects. Can someone give some rough idea on how to do this? before I dig into the source codes, since i have only some academic experiences on molecular dynamics DEM simulations mainly based on 3D spheres.


Proper sphere collision resolution? I am implementing a sphere to sphere collision resolution and I am a little confused on where to start. First question, is there a standard way that games engines do sphere to sphere collision resolution? Is there only like a couple standard ways to do it? Or does the resolution vary very heavily based on whats needed? I want to implement this in my engine and I wrote a basic one that pushes a sphere and another sphere (so basically the one interacting can push the other) but this was just a super simple concept. How exactly can I improve this to make it more accurate? (Mind you the code isn't optimized since I am still testing) It seems like there is a lack of solid documentation on collision resolution in general as it's a more niche topic. Most resources I found only concern the detection part. bool isSphereInsideSphere(glm vec3 sphere, float sphereRadius, glm vec3 otherSphere, float otherSphereRadius, Entity e1, Entity e2) float dist glm sqrt((sphere.x otherSphere.x) (sphere.x otherSphere.x) (sphere.y otherSphere.y) (sphere.y otherSphere.y) (sphere.z otherSphere.z) (sphere.z otherSphere.z)) if (dist lt (sphereRadius otherSphereRadius)) Push code e1 gt move( e1 gt xVelocity 2, 0, e1 gt zVelocity 2) e2 gt move(e1 gt xVelocity 2, 0, e1 gt zVelocity 2) return dist lt (sphereRadius otherSphereRadius)


Sphere intersection Stuck I have two spheres that are bounded by spheres for collision detection. I do not want them to intersect. My intersection works. But it gets stuck. Once the function returns true, I cannot get it out. I tried collideBool ObjectOne.Intersect(ObjectTwo) if(collide true) leftright leftright updown updown else if(GetAsyncKeyState(VK RIGHT)) leftright dt if(GetAsyncKeyState(VK LEFT)) leftright dt if(GetAsyncKeyState(VK DOWN)) updown dt if(GetAsyncKeyState(VK UP)) updown dt collide false My sphere gets stuck. What is a way around this?


3D line segment AABB collision, with hit normal? I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily sized. I also need the surface normal of the AABB, if there was a hit. From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame. I have struct AABB VEC3F min VEC3F max a and b representing start end points of the line segment returns true if intersects, also fills out "normal" if true bool LineIntersectsAABB(const VEC3F amp a, const VEC3F amp b, const VEC3F amp inv dir, const AABB amp aabb, VEC3F normal) The implementations I've found either do not find the hit normal, and or they're intended for boxes cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations.


Custom Tile Collision Detection Has Trouble With Edges So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it). The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence http i.imgur.com CACfhIP.gifv I have narrowed this down to this specific segment of code (Please note that SPRITE WIDTH is 20, which also means 20 pixels) BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) round down to a multiple of SPRITE WIDTH else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) ditto but up The problem seems to be that both parts of the if...else if... statement require the equality symbol to work correctly. Meaning that in the provided example, the fall through glitch will happen to the tile on the left instead if I move the equality symbol to the else if portion. I attempted to fix this issue by adding an else clause and removing the equality from the if...else if... parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) else if (newX SPRITE WIDTH gt SPRITE WIDTH 2) roundedX roundDownTo(newX, SPRITE WIDTH) else roundedX roundUpTo(newX, SPRITE WIDTH) But this created an even stranger case where the middle part of the tile would cause a fall through but the edges would work correctly on both the left and the right tile. This can be seen here http i.imgur.com lTaUuzh.gifv I've been at this all day (literally), I appreciate any help you can provide. If I have not provided enough information, please let me know and I will do my best to provide it.