_id
int64
0
49
text
stringlengths
71
4.19k
18
Predictive Collision Detection Find Time Of Impact I have a green box at a starting position A. It can move along two paths A to B is linear motion A to C is under the influence of gravity (non linear) The thin vertical line is a fixed colliding wall. All objects are represented with axis aligned AABB bounding boxes. For the path A to B, if my understanding is correct, I (think I) can determine the time of impact (T0) on the wall based on swept AABB collision techniques. this case simply reduces to motion along x axis, and time of impact can be calculated easily. My question is for path A to C. Under the influence of gravity how can I determine the time of impact (T1) relative to the starting time T at location A. (The motion of A to C can be predicted using the standard equations of motion) Are there any techniques algorithms available for this? EDIT To clarify the vertical wall is illustrative walls can be arbitrarily vertical or horizontal or both (like a corner). They will be stationary, and axis aligned though.
18
Unity Particle System collision detection problem I'm using Unity 3.5.5f3 wich has the Shuriken particle system. I've made a blood particle system based on Unity's demos. (Exploding paint Blood ) The blood is flowing and when it collides with a Plane Transform wich I've created a small pool of blood spawns as a Collision Sub Emitter. My main problem is that when I want to add another object to collide it just doesn't want to work. When I create a cube, and set it as a collision plane the collision will only occur at the half of the cube. I want this to happen When it reaches the cube's surface the sub emmiter activates, and when the surface is horizontal it appears horizontally, and if it's vertical then vertically. Now it just appears horizontally everytime like in the picture. How could I solve it?
18
Collision detection without classes, in Pygame I am writing a game in Pygame and want to get collision detection working. The aim is that when an object hits another, the target object disappears. I want to avoid having classes for now, to keep things simple. This makes it difficult to get collision detection working, because the Rect method in Pygame assumes classes. The logic I want to achieve is if object hits a target object target object disappears What's the minimal code I'd need to achieve this?
18
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?
18
Finding roots zeros for collision detection? For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the x y Cartesian plane, but am now interested in understanding the basics of a priori collision detection... In the link here, I noticed the reference to Newton s Method. So, I want to better understand the link b w finding zeros of an equation and detecting a posteriori collision. Let's start with the most obvious case of finding roots of an equation If you have a projectile's trajectory modeled as a quadratic function, you can find the roots to predict at what time the height will equal zero (or any other constant height, actually, by just solving f(x) C to be f(x) C 0 and then finding roots of that expression). So, as I understand, finding the root can tell me the time at which the object will be at any chosen height. More broadly, we basically know the (x,y) location of the object for any given time. But how does root finding, in particular, translate to detecting collisions with another object? (The other object may be stationary, or be moving. If the latter, do you also determine roots location of this moving object as well? Calculate the (x,y) trajectory of both objects and determine where they will intersect?) Again, the basic question is where does root finding come into play? Any links to a basic primer on this topic, with a simple example would also be greatly appreciated.
18
How to implement 2d collision detection that is immune to low framerate and fast movement? I am trying to implement my own collision detection for a 2.5d voxel style platformer using Three.js. I have a problem with my implementation if the framerate is too low or the character is moving too fast (usually when falling from high places) it falls right through. Is there a way to improve collision detection to be immune to problems like this? This is how I detect collisions function render() requestAnimationFrame(render) setVelocity() animate() manageCollisions() renderer.render(scene, camera) function manageCollisions() Check every game object for collision gt TODO implement broad phase when dealing with many objects for(i 0 i lt world.length i ) Check for bottom collision lt ALWAYS check (unless moving up) if(velocityY lt 0) if( (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("bottom collision " i) velocityY 0 jumped false grounded true character.position.y world i .position.y world i .height 2 character.height 2 0.1 0.1 prevents shaking else grounded false Check for right collision lt ONLY if moving right (velocityX is positive) if(velocityX gt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("right collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for left collision lt ONLY if moving left (velocityX is negative) if(velocityX lt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2)) console.log("left collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for top collision lt ONLY if moving up (velocityY is positive) if(velocityY gt 0) if( (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("top collision" i) velocityY 0 character.position.y world i .position.y world i .height 2 character.height 2
18
How do I determine the collision normal in an axis aligned bounding box collision? I have a 3d moving box and a stationary box. I can detect collisions ok but now I would like to slide the moving box against the stationary box as a collision response. For this I need the normal of the face that collides with the moving box. Does anyone know how I figure this out? It doesn't seem like the collision test gives me this information. Any help is appreciated.
18
Tile based collision detection errors if player is smaller than tiles I have implemented a tilemap where each tile is at a non negative x and y position. (So at the moment think like chess) At the moment a tile is 16, 16 pixels in size Tile 0,0 is at the left bottom corner Some tiles should be collidable. I've never implemented something like that and during research stumbled upon https jonathanwhiting.com tutorial collision The general idea collision response handling let mut new pos Point2 new(curr pos.x x offset, curr pos.y) let collision on x collide with world( amp new pos, amp world) if !collision on x transform.translate x(x offset) new pos.y curr pos.y y offset let collision on y collide with world( amp new pos, amp world) if !collision on y transform.translate y(y offset) The collision detection fn collide with world(new pos amp Point2 lt f32 gt , world amp World) gt bool TODO make these sizes i16 instead so we can grow in any direction! let mut left tile u16 (new pos.x TILE SIZE IN PIXELS as f32) as u16 1 so that we do not collide until we are exactly at the thing let mut right tile u16 ((new pos.x PLAYER WIDTH 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut top tile u16 ((new pos.y PLAYER HEIGHT 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut bottom tile u16 (new pos.y TILE SIZE IN PIXELS as f32) as u16 println!("new pos ? , left , right , top , bottom ", (new pos.x, new pos.y), left tile, right tile, top tile, bottom tile) Useless as long as we use unsigned coordinates if left tile lt 0 left tile 0 if right tile gt WORLD WIDTH IN TILES right tile WORLD WIDTH IN TILES Useless as long as we use unsigned coordinates if bottom tile lt 0 bottom tile 0 if top tile gt WORLD HEIGHT IN TILES top tile WORLD HEIGHT IN TILES let mut any collision false for i in left tile.. right tile for j in bottom tile.. top tile let tile world.get tile(i, j) println!("tile at ? is ? ", (i, j), tile) match tile Some(tile) gt if tile WALL println!("hit a wall at ? !", (i, j)) any collision true None gt (), return any collision I basically took (or tried to take) the optimised version of the linked blog entry. Now to the problems If PLAYER WIDTH and PLAYER HEIGHT are both 16.0 collision works fine But note that I had to put 1.0 in the calculation of the right tile and top tile, else the collision for UP and RIGHT would occur one pixel to early (so the player would never touch walls to their top or right) This change alone makes me a bit suspicious looks like I made an error there. The real problems start if the player is smaller than a tile In the following screenshots the following rules apply ) the PLAYER WIDTH and PLAYER HEIGHT are both 8 ) Greenish tiles are the only walls! ) All the screenshots were taken in ONE run no parameters were changed during this run! 1) Trying to collide with right tile overlapping 2) Trying to collide with top tile cannot go any nearer than 4 pixels (half the height of the player) 3) Trying to collide with left tile cannot go any nearer than 4 pixels (half the width of the player) 4) Trying to collide with top tile suddenly overlapping although different tile didn't collide? 5) Trying to collide with bottom tile cannot go any nearer than 4 pixels I cannot grasp 2 and 4 at the moment.
18
Collision Resolution of Axis Aligned Bounding Boxes that Change Size I am developing an action platformer in Python, with Pygame. That said, my question is a general one about collision resolution strategies. I use an axis aligned bounding box for the purposes of collision detection. The bounding box changes sizes depending on the sprite's action and the frame of the action's animation. When I update my sprite's position, I first update the y coordinate, check for and resolve collision in the y direction, then do the same for the x coordinate. When I resolve collision, I simply move the bounding rect's sides to align flush with the appropriate walls. Because the bounding rect changes sizes throughout my animations, I am noticing buggy behavior in certain situations when the frame moves from a smaller one to a larger one. The change of frame results in the sprite intersecting a wall and his position is resolved such that he falls off the map. Here is a diagram illustrating the problem It doesn't matter whether I resolve in the x direction or the y direction first. They result in reciprocal buggy behavior when the next frame is wider or taller, respectively. My question concerns general collision resolution strategies for axis aligned bounding boxes that change size and shape. What are the best algorithms for collision resolution that avoid this issue? Here are some of the functions and values I have access to colliderect tests if two rectangles collide collidepoint boolean that tests if a point collides with a rectangle rect.topleft, rect.topright, rect.bottomleft, rect.bottomright, rect.center, rect.centerx, rect.centery various points on the rectangles rect.left, rect.right, rect.top, rect.bottom values for the sides of the rects various vectors in short, the usual stuff Apologies if this question is a dupe. I imagine it is a pretty common one, though I couldn't find anything that helped me specifically.
18
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
18
Is it possible to detect contact with every frame change when using an animation in SpriteKit? Is it possible to detect contact with every frame change when using an animation in SpriteKit? For example, if I have two nodes of a person walking, I want to detect contact with the ground each time the frame changes (the character is walking on a surface). Just can't seem to get it. I've tried using a for loop to add a physics body and the contact and collision properties to each node, but that doesn't seem to work. It detects contact once, but that's it. Anyone have any ideas? Thanks in advance!
18
Creating runtime mesh colliders for roads in Unreal Engine 4 I want to create several mesh colliders in game at runtime. By mesh colliders I mean "complex collision". The meshes are for curved roads. The roads will be rendered using hierarchichal instanced static mesh, the visible road meshes will be high poly detailed meshes. For collision purpose I will create simple low poly meshes at runtime and I want collision checks for them. I also want these meshes to be stored in single actor for easy handling. Is there any existing class or plugin that does this, or a way to implement it myself? I have checked procedural mesh component and runtime mesh component but they don't seem to have what I want.
18
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.
18
Mesh level acceleration structures for collision detection when mesh instances can be rotated, scaled and or resized Short version in the mid phase or narrow phase of collision detection, does any acceleration structure organizing the mesh's vertices (e.g. AABB trees, Octrees, Quadtrees) work for the mesh's instances that are re scaled, re sizes and or rotated? Long version suppose a concave mesh composed of a very high number of triangles (e.g. 200k) and for which I cannot use convex decomposition in order to perform collision detection. The most efficient solution usually employed would be to organize the vertices of the mesh using acceleration structures to quickly prune which parts of the mesh are likely to have been collided with. However, that mesh is used for generating instantiated copies and each of these can have different size, rotation and or scale at any of the X,Y,Z axis. Would any acceleration structures work since the instances can be re scaled, rotated and resized? Suggestions, tips, academic references, are all appreciated.
18
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.
18
Self colliding cloth physics I've previously simulated cloth using Verlet integration but couldn't successfully get the cloth to collide with itself in an efficient way. The reason being is because I used a brute force algorithm to if check all the cloth points collided with each other. My question is how could I efficiently check for collision between the cloth points? I thought of using some sort of tree structure but it doesn't really make sense in my head given that a lot of tree structures largely depend on spatial position or don't actually suit the cloth because they're better suited to static geometry(BSP). Additional Info The cloth is logically just a 2D array of points tied together by a constraint. The cloth is affected by wind and gravity and is also anchored in space at the two upper corner
18
What causes player box world geometry glitches in old games? I'm looking to understand and find the terminology for what causes or allows players to interfere with geometry in old games. Famously, ID's Quake3 gave birth to a whole community of people breaking the physics by jumping, sliding, getting stuck and launching themselves off points in geometry. Some months ago (though I'd be darned if I can find it again!) I saw a conference held by Bungie's Vic DeLeon and a colleague in which Vic briefly discussed the issues he ran into while attempting to wrap 'collision' objects (please correct my terminology) around environment objects so that players could appear as though they were walking on organic surfaces, while not clipping through them or appear to be walking on air at certain points, due to complexities in the modeling. My aim is to compose a case study essay for University in which I can tackle this issue in games, drawing on early exploits and how techniques have changed to address such exploits and to aid in the gameplay itself. I have 3 current day example of where exploits still exist, however specifically targeting ID Software clearly shows they've massively improved their techniques between Q3 and Q4. So in summary, with your help please, I'd like to gain a slightly better understanding of this issue as a whole (its terminology mainly) so I can use terms and ask the right questions within the right contexts. In practical application, I know what it is, I know how to do it, but I don't have the benefit of level design knowledge yet and its technical widgety knick knack terms )
18
Complex collisions in pygame I've seen many tutorials for simple rectangle or circle based collision detection with pygame. But how can I do more complex collisions with arbitrary polygons? Is the only option pixel based collision detection?
18
RK4 integration and Continuous Collision Detection I'm using this method to detect collision between two AABBs. The algorithm is simple, fast and works great. It uses the relative velocity between the two objects to calculate TOI. This works fine with Euler, but now i'm trying to switch to RK4, which makes it hard for me to determine the TOI since i can't just divide the distance between the two AABBs by their relative velocity. Since RK4 is so popular, how do people deal with this issue? How to calculate a TOI for a swept AABB with RK4?
18
Separating Axis Theorem and rotated objects Quick question which hopefully won't require thralling through my code. I have a working implementation of SAT for 3D collision detection but I'm having some problems with dealing with rotated objects. So what I have done, is every frame I rotate every point in both objects by their rotation quaternions. This feels excessive, especially if I am going to be translating scaling rotating every vertex in every object on every frame for the collision detection. I would hope there's a way of implementing my SAT implementation to work with rotated normals only, and not need the rotated projections to compensate, but that doesn't seem to be working. Could anyone provide me with a brief explanation with how SAT should be expected to handle rotations? Can we rotate certain points, or perhaps get some sort of post projection rotation value to skew our projections like we can with translations? Thanks
18
Exact collision detection for high detail deformable triangular meshes What robust methods or approaches exist for exact collision detection involving high detail, deformable geometry? The kind of mesh I am describing is a surface that is specified as a triangulated polyhedron and looks very similar to this For the specific application I am working on, I need to find all the contact points for colliding meshes that undergo subsequent deformation. Possible deformations that may occur during a collisional event 1) the mesh decomposes, or fragments into smaller (triangulated) meshes 2) the mesh retains integrity but the vertex values of it's surface change 3) both of the above deformations occur There is no real time constraint accuracy rather than performance is the critical factor.
18
Why does my character stop a little before landing on the ground? I made a little game with side scrolling and a box (the player) jumping across the level. The simple physics are almost done, but I have two problem with the way things behave On landing, the box takes a little time to reach the floor When the box hit a roof, there is always a little space between it and the object. Here is my collision code (in the player's Step Event) myGravity 0.5 if (vspeed gt 10) vspeed 10 speedAir abs(vspeed 1) ON FLOOR !(place free(x, y speedAir)) ON AIR place free(x, y speedAir) FREE RIGHT place free(x speedScreen, y) FREE UP place free(x, y speedAir) KEY UP keyboard check(vk up) KEY LEFT keyboard check(vk left) KEY RIGHT keyboard check(vk right) KEY FIRE keyboard check(vk space) JUMP if ON AIR gravity myGravity gravity direction 270 if !(FREE UP) vspeed 0 else if ON FLOOR gravity 0 gravity direction 270 vspeed 0 JUMP if KEY UP amp FREE UP vspeed 10 LATERAL if (FREE RIGHT) x speedScreen screen side scrolling How can I do this correctly?
18
Unity, changing gravity game stopping character when he hit a wall I am currently working on a 2d puzzle game in the unity engine. One of the aspect of this game is the possibility to rotate the level of 90 . It also rotate the gravity. The main character is not directly controlled by the player, but instead falls when the level is rotated. When the main character hits a wall, he should stop to moving. If I do not stop it, it kind of blinks and shakes against the wall. To stop it I detect collision and depending on the current rotation state, the player will stop at "vertical" or "horizontal" tags when a OnCollisonEnter occurs. I must do that because when the player falls on his relative ground, he must not stop like if he had touched a wall. My problem is the 'side' of platform, or the 'top' of wall, they use the same tag and thus do not give the correct tag to my character. I tried to put a very small invisible box on top side of elements but the collision occurs nevertheless. It seems when the player falls and hit something he go through a bit before being replaced at correct position by unity. Is there a way 1 ) to not stop my character but to make it appear immobile on screen 2 ) To detect a "I cannot move anymore" collision other than by using collision?
18
How to create walls and rooms with Pixi I'm a JS dev but pretty new to Pixi and 2D developemnt so please bear with me as I explain this. I want to write a simulator for short path finding (for evacuation purposes). I decided to use Pixi.js for this since it seems capable of doing everything I need to do. I followed this tutorial to try to learn how Pixi works and if its right for this. The tutorial didn't seem to answer many questions I have and I still have some confusion. Before I dive into writing the code, I want to know how wall detection in Pixi acheived. Take the below map for example It is a 800 x 800 png file (where everything but the blue is transparent no grid lines ) that i can load into Pixi as a Sprite. I created it in Tiled editor. So it can be exported as a tilemap, JSON, CSV etc. When I export it as JSON, here is the file contents https pastebin.com zGh1XmR7 The blue boxes represent walls. I want to load in other various sprite objects so that it will look like this The people in the simulations cannot cross the blue walls and they cannot cross the pink circles (they represent danger zones). I intend to use easystar.js to find the shortest path to exits for the people sprites in the map. So my question is this, how does Pixi recognise the blue walls? Is it something I have to do when creating the tileset png? Like something defined in the JSON file for the tileset atlas? Maybe SVG? Or is there a pixi function to do this? Is this the best approach to doing this and is Pixi even the best way to do this? I'm looking for a tried and tested solution or a pointer in the right direction.
18
Detecting walls or floors in pygame I am trying to make bullets bounce of walls, but I can't figure out how to correctly do the collision detection. What I am currently doing is iterating through all the solid blocks and if the bullet hits the bottom, top or sides, its vector is adjusted accordingly. However, sometimes when I shoot, the bullet doesn't bounce, I think it's when I shoot at a border between two blocks. Here is the update method for my Bullet class def update(self, dt) if self.can bounce if the bullet hasnt bounced find its vector using the mousclick pos and player pos speed 10. range 200 distance self.mouse x self.player 0 , self.mouse y self.player 1 norm math.sqrt(distance 0 2 distance 1 2) direction distance 0 norm, distance 1 norm bullet vector direction 0 speed, direction 1 speed self.dx bullet vector 0 self.dy bullet vector 1 check each block for collision for block in self.game.solid blocks last self.rect.copy() if self.rect.colliderect(block) topcheck self.rect.top lt block.rect.bottom and self.rect.top gt block.rect.top bottomcheck self.rect.bottom gt block.rect.top and self.rect.bottom lt block.rect.bottom rightcheck self.rect.right gt block.rect.left and self.rect.right lt block.rect.right leftcheck self.rect.left lt block.rect.right and self.rect.left gt block.rect.left each test tests if it hit the top bottom left or right side of the block its colliding with if self.can bounce if topcheck self.rect last self.dy 1 self.can bounce False print "top" if bottomcheck self.rect last self.dy 1 Bottom check self.can bounce False print "bottom" if rightcheck self.rect last self.dx 1 right check self.can bounce False print "right" if leftcheck self.rect last self.dx 1 left check self.can bounce False print "left" else if it has already bounced and colliding again kill it self.kill() for enemy in self.game.enemies list if self.rect.colliderect(enemy) self.kill() update position self.rect.x self.dx self.rect.y self.dy This definitely isn't the best way to do it but I can't think of another way. If anyone has done this or can help that would be awesome!
18
2D moving sprites collision I'm trying to create a game where i have two abjects A and B 1 I know the shape of the two objects(Rectangles) . 2 The speed and position of each object. And i'm trying to figure out if the two object will eventually collide . I calcuted the point where the object's paths intersect using this formula The same for y But i still don't know if the two object will actually collide or will miss each other .
18
Collision detection optimization for a top down shooter I'm relatively new to game development and have been trying to learn how collision detection is coded. I mostly work with Actionscript 3, but I'm learning C on the side. I've been wondering how "bullet hell" and top down shooters optimize their collision detection with so many objects. Any information theories would be great.
18
How to make object that moves with constant speed not overshoot the object it collides with? To learn LOVE2D I am creating a simple project. Player moves the square with arrows keys until it hits the goal square, at which point the game is won. function isCollision(x1,y1,w1,h1,x2,y2,w2,h2) return (x1 lt x2 w2)and(x2 lt x1 w1)and(y1 lt y2 h2)and(y2 lt y1 h1) end function love.update(dt) if love.keyboard.isDown("escape") then love.event.quit() end if isCollision(player.x,player.y,player.w,player.h,goal.x,goal.y,goal.w,goal.h) then gameOver true if love.keyboard.isDown("space") then love.load() end else delta player.speed dt if love.keyboard.isDown("right") and player.x lt 800 player.w then player.x player.x delta end if love.keyboard.isDown("left") and player.x gt 0 then player.x player.x delta end if love.keyboard.isDown("down") and player.y lt 600 player.h then player.y player.y delta end if love.keyboard.isDown("up") and player.y gt 0 then player.y player.y delta end end end But sometimes the square overshoots the goal and it becomes lodged in the goal. How do I make it so that engine detects when the player simply touches the goal and stops there, without moving further in the frame? Disclaimer Using a collision detection library like bump.lua would be too easy. I want to learn the relevant practices so that I can apply it to retro consoles and computers in the future.
18
Calculate diameter of sphere large enough to encompasss a frustum I'm attempting to speed up box to box collision checks by first testing if two spheres large enough to encompass each (respectively) would collide (because I'm using separating axis theorem and it's slower than I'd like it to be). This is fine for equilateral boxes (ie, cubes) since I can just take two opposing corners and the line between them is the exact diameter of a sphere big enough to encompass the whole thing properly and also the point in it's middle is the origin of the sphere. I add an epsilon just to avoid any glitches with colliding with the corners of the cube, but theoretically it shouldn't be necessary. But for non equilateral boxes, such as frusta, this method does not work. I've pondered it over and nothing I can come up with is a quick enough calculation for my taste. The best I've come up with is to take two opposing edges (diagonally through the box) from the near face to the far face, get their individual lengths and sum them then do the same thing for the left to right faces and top to bottom faces. with these three sums, take the largest and just use that. Anyway, that method works but it's too much calculation, involving 6 square roots. I need something faster and preferably more accurate. I've googled and haven't found much on this subject at all. I'd like the solution to work for boxes of any shape (as long as faces are valid) and frustums of unknown orientation (meaning the large face could be any side, not a known one). It's also important to know the origin of the sphere (which is the dead center of the frustum). Which if there is no faster calculation, this is just the sum of all 8 verts divided by 8. Any ideas?
18
how to keep display tick rate steady when using continuous collision detection? (I've just found about this forum). I hope it is ok to repost my question again here. I posted this question at stackoverflow, but it looks like I might get better help here. Here is the question I've implemented basic particles motion simulation with continuous collision detection. But there is small issue in display. Assume simple case of circles moving inside square. All elastic collisions. no firction. All motion is constant speed. No forces are involved, no gravity. So when a particle is moving, it is always moving at constant speed (in between collisions) What I do now is this Let the simulation time step be 1 second (for example). This is the time step simulation is advanced before displaying the new state (unless there is a collision sooner than this). At start of each time step, time for the next collision between any particles or a particle with a wall is determined. Call this the TOC time let s say TOC was .5 seconds in this case. Since TOC is smaller than the standard time step, then the system is moved by TOC and the new system is displayed so that the new display shows any collisions as just taking place (say 2 circles just touched each other s, or a circle just touched a wall) Next, the collision(s) are resolved (i.e. speeds updated, changed directions etc..). A new step is started. The same thing happens. Now assume there is no collision detected within the next 1 second (those 2 circles above will not be in collision any more, even though they are still touching, due to their speeds showing they are moving apart now), Hence, simulation time is advanced now by the full one second, the standard time step, and particles are moved on the screen using 1 second simulation time and new display is shown. You see what has just happened One frame ran for .5 seconds, but the next frame runs for 1 second, may be the 3rd frame is displayed after 2 seconds, may be the 4th frame is displayed after 2.8 seconds (because TOC was .8 seconds then) and so on. What happens is that the motion of a particle on the screen appears to speed up or slow down, even though it is moving at constant speed and was not even involved in a collision. i.e. Looking at one particle on its own, I see it suddenly speeding up or slowing down, becuase another particle had hit a wall. This is because the display tick is not uniform. i.e. the frame rate update is changing, giving the false illusion that a particle is moving at non constant speed while in fact it is moving at constant speed. The motion on the screen is not smooth, since the screen is not updating at constant rate. I am not able to figure how to fix this. If I want to show 2 particles at the moment of the collision, I must draw the screen at different times. Drawing the screen always at the same tick interval, results in seeing 2 particles before the collision, and then after the collision, and not just when they colliding, which looked bad when I tried it. So, how do real games handle this issue? How to display things in order to show collisions when it happen, yet keep the display tick constant? These 2 requirements seem to contradict each other s.
18
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.
18
How to calculate rect moving in a curved path collision detection I'm trying to find the best way to use collision detection for a rect moving in a curved path here is example of what i have I found few methods and I have hard time to find what is the best way. I have the pure calculation method that is here http devmag.org.za 2009 04 13 basic collision detection in 2d part 1 and I also have the pixel perfect method that is here http blog.muditjaju.infiniteeurekas.in ?p 1 I'm using cocos2d x but it can be in any engine or language. What is the best method for this?
18
Issue with 2d Angular Car Collision Response I am having trouble getting the angular collision response to work properly in my 2d car simulation. I have gotten the linear collision response to work between the vehicles, however, the angular collision response does not seem to be working. The problem seems to arise from my slip angle calculation for the car, and it seems to override the angular impulse. The slip angle is necessary to make the vehicle move realistically. Here's the code to calculate the slip angle Calculate slip angle for front back wheel this.wheels.front.slipAngle Math.atan2(this.localVelocity.y yawSpeedFront, Math.abs(this.localVelocity.x)) this.wheels.back.slipAngle Math.atan2(this.localVelocity.y yawSpeedRear, Math.abs(this.localVelocity.x)) As can be seen in the following pictures, the car rotation response is correctly simulated when it hits the top of the car and rotates clockwise. On the other hand, when the car hits the bottom of the other car, the rotation should be clockwise, but actually still goes clockwise. It seems to me that the problem arises because the slipAngle overrides the angular rotation of the collision. My project can be seen here https victorwei.com projects car sim Feel free to take play around with the simulation and view the code to figure out the issue. If there are any suggestions on how to mitigate this problem, that would be greatly appreciated.
18
Detecting collision of multiple moving objects I have wrote a simple game that has a 100 balls bouncing off the borders of the canvas. Each ball is an instance of ball class function that has the following definition var cnv document.getElementById("mycanvas") var ctx cnv.getContext("2d") ... ... function ball() at instantiation, set the ball in a random position this.x parseInt(Math.random() cnv.width) 1 this.y parseInt(Math.random() cnv.height) 1 this.size parseInt(Math.random() 10) 1 and give the ball a random speed at a random direction this.x speed parseInt(Math.random() 10) 1 this.y speed parseInt(Math.random() 10) 1 if (this.x speed gt 5) this.x speed 1 if (this.y speed gt 5) this.y speed 1 draw() and update() for the instance will be called from the main game loop this.draw function() ctx.beginPath() ctx.fillStyle "white" ctx.arc(this.x,this.y,this.size,0,Math.PI 2,true) ctx.fill() this.update function() this.x this.x speed this.y this.y speed if (this.x gt cnv.width this.x lt 0) this.x speed 1 if (this.y gt cnv.height this.y lt 0) this.y speed 1 In the main game loop, I call gameUpdate() which in turn calls update() for each ball, like so var balls array to hold all instances ... ... function gameStart() for(var i 0 i lt 100 i ) balls.push( new ball() ) create an instance and store its reference function gameUpdate() for(var i 0 i lt balls.length i ) balls i .update() this ensures that each ball moves on its own Now my question is How can I manage to detect collision between all of the instances of balls ? Here is my attempt, but I already know it is not efficient function detectCollision() for(var i 0 i lt balls.length i ) for(var j 0 j lt balls.length 1 j ) if (i ! j) make sure we have two different balls to check with assuming that collision() exists and checks x,y for each parameter and return boolean if (collision(balls i ,balls j )) console.log("boom!") What is a better way for checking collision of moving objects?
18
How can I cancel a contact in a b2ContactListener? To know when contacts happen we can derive from b2ContactListener and implement our own solution which is great. I'm wondering is there anyway we can cancel a contact, that is to say when we hit begin contact we call a function or do something to destroy the contact before it has a chance to be resolved? My game logic relies on setting any number of collision groups (which are basically integers). Collision groups can have settings to interact with one another, for example collision group 41 and 13 may be set to never collide while group 41 and 56 will collide. Some groups which are set not to collide are still meant to generate an OnContact callback (but will obviously never get to end contact).
18
HTML5 platformer collision detection problem I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code. I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here Platform engine test. Arrow keys move and z run, x jump, c shoot. Try to jump into the first pit and slide on the wall. Here's the collision detection code function checkCollisions(a, b) if ((a.x gt b.x b.width) (a.x a.width lt b.x) (a.y gt b.y b.height) (a.y a.height lt b.y)) return false else handleCollisions(a, b) return true function handleCollisions(a, b) var a top a.y, a bottom a.y a.height, a left a.x, a right a.x a.width, b top b.y, b bottom b.y b.height, b left b.x, b right b.x b.width if (a bottom a.vy gt b top amp amp distanceBetween(a bottom, b top) a.vy lt distanceBetween(a bottom, b bottom)) a.topCollision true a.y b.y a.height 2 a.vy 0 a.canJump true else if (a top a.vy lt b bottom amp amp distanceBetween(a top, b bottom) a.vy lt distanceBetween(a top, b top)) a.bottomCollision true a.y b.y b.height a.vy 0 else if (a right a.vx gt b left amp amp distanceBetween(a right, b left) lt distanceBetween(a right, b right)) a.rightCollision true a.x b.x a.width 3 a.vx 0 else if (a left a.vx lt b right amp amp distanceBetween(a left, b right) lt distanceBetween(a left, b left)) a.leftCollision true a.x b.x b.width 3 a.vx 0 function distanceBetween(a, b) return Math.abs(b a)
18
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.
18
How to differentiate between colliding objects in Box2D? I need to differentiate between different points of contact in my racing game. I currently have staticSensors which determine if the car is on the track or not, but I have created a second sensor to act as the 'finish line' but I am not sure how to differentiate the contact between the 'checkeredFlag' and all of the other sensors? Any help would be appreciated! Here is my code include "contactListener.h" void ContactListener BeginContact(b2Contact contact) b2Body bodyA contact GetFixtureA() GetBody() b2Body bodyB contact GetFixtureB() GetBody() bool isSensorA contact gt GetFixtureA() gt IsSensor() bool isSensorB contact gt GetFixtureB() gt IsSensor() Wheel wheel (Wheel )bodyA gt GetUserData() CheckeredFlag flag (CheckeredFlag )bodyB gt GetUserData() if (isSensorA) StaticSensor sensor static cast lt StaticSensor gt (bodyA gt GetUserData()) sensor gt action() Wheel wheel static cast lt Wheel gt (bodyB gt GetUserData()) wheel gt offRoad() return if (isSensorB) StaticSensor sensor static cast lt StaticSensor gt (bodyB gt GetUserData()) sensor gt action() Wheel wheel static cast lt Wheel gt (bodyA gt GetUserData()) wheel gt offRoad() return if (typeid(CheckeredFlag).name() typeid(bodyA).name()) if (typeid(Wheel).name() typeid(bodyB).name()) flag gt action() return
18
Understanding unknown mesh data structure I have a large number of old mesh files in a custom, undocumented binary format. I have managed to parse almost everything but am left with one group of structures, described below, that I don't understand. I hope an experienced graphics programmer can explain what is happening. Here are the structures concerned These types are defined below. We're trying to understand what these three arrays are used to achieve. VertexRef vertexRefs Triangle triangles Unknown unknowns struct VertexRef Earlier in the file, there are several vertex buffers. The file can contain multiple meshes, either as components of a larger mesh, or as multiple LODs. This value group picks out one of these buffers. uint8 t group Index into the vertex buffer picked out by group . uint16 t vertexIndex struct TriangleVertex Index into the array vertexRefs uint16 t vertexRef Index into the array unknowns uint16 t unknownIndex struct Triangle TriangleVertex verts 3 struct Unknown Index into the array vertexRefs uint16 t vertexRef1 Index into the array triangles uint16 t triangleIndex1 Another index into the array vertexRefs uint16 t vertexRef2 triangleIndex2 can be 0xffff, while triangleIndex1 never is uint16 t triangleIndex2 The array of VertexRef is straightforward. It picks vertices, potentially from multiple meshes, to form a composite mesh. The array of Triangle is formed by vertices from the array of VertexRef. Each vertex is also associated with an Unknown. I am out of my depth in understanding what Unknown is doing. Member triangleIndex2 sometimes being 0xffff (or invalid, or nonexistent?) might indicate it is a leaf node of a tree? Perhaps the structure comprising the arrays vertexRefs, triangles and unknowns is some kind of collision detection tree? I'd be very grateful for any hints. Please ask questions if I've failed to be clear enough about something. Edit In answer to a request in comments, I am attaching a sample file and code to load it. The code should run on any likely system. The file is a mesh of a pair of boots. The file is hosted at uploadfiles.io https ufile.io w66mh
18
What data should a generic collision detection system gather? I'm working on a relatively generic 2D AABB collision detection system for a game engine, and I've re written it more times than I'd like to admit, due to not calculating or recording specific details of each collision. Right now, this is what I'm collecting Collision time as a fraction of an update cycle in the game loop. Location of the collision. ID of the colliding object. Each object has a Set that holds this data for each collision (I'm working with a component entity system) so other systems can use the recorded data. The problem I just ran into was that I needed to know which side of the object the collision takes place on. What other values or points of interest should I calculate or record, per collision? What do you look for in a standard collision detection system?
18
How would I move something around inside of a sphere without it going outside of the sphere? I want to be able to do this, but not go outside of the 4.4 meter limit, the radius is 4.4 meters, and it has zero gravity and no friction. I have a hard time explaining this, but imagine holding a hollow sphere with a little ball inside, when you shake it around the ball goes around the inside, I need something like that, but with zero gravity and no friction. I wasn't really sure how to do this, but I tried void Slide() if (slide) for (uint32 t deviceIndex 0 deviceIndex lt vr k unMaxTrackedDeviceCount deviceIndex ) glm vec3 position devicePos deviceIndex .xyz() if (sqrt(pow(position.x 0.35, 2) pow(position.y 1.75, 2) pow(position.z 0.85, 2)) gt 4.4) if (abs(position.x) gt abs(position.y) amp amp abs(position.x) gt abs(position.z)) if (position.x gt 0) velocity.x ((abs(velocity.y)) (abs(velocity.z))) 2 else velocity.x ((abs(velocity.y) 1) (abs(velocity.z) 1)) 2 if (abs(position.y) gt abs(position.x) amp amp abs(position.y) gt abs(position.z)) if (position.y gt 0) velocity.y ((abs(velocity.x)) (abs(velocity.z))) 2 else velocity.y ((abs(velocity.x) 1) (abs(velocity.z) 1)) 2 if (abs(position.z) gt abs(position.x) amp amp abs(position.z) gt abs(position.y)) if (position.z gt 0) velocity.z ((abs(velocity.x)) (abs(velocity.y))) 2 else velocity.z ((abs(velocity.x) 1) (abs(velocity.y) 1)) 2
18
Adding collisions to a 3D mmorpg game I'm creating a mmorpg game with a little team, and we want to add a player objets collisions system. We want players to be able to walk on a heightmap ground, and walk be blocked by objects. I found the bullet physics library (I already used his Java wrapper), but I don't know how to make it enough efficient for a VERY huge map, and a lot of players on it. In this game, there will be a very huge world (loaded by a chunk system), with all players on the same world. So how can I made an efficient way to make player(AABB) objects(shapes with triangles) collision system in a very big map?
18
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?
18
Seeking Advice Collision with JBox2d for Top Down or Isometric Maps I Hope I can make this as clear as possible! Currently working on an action RPG game, very early stages, more just the basic ideas down and written in. So i'll start on with my setup Using Java with LibGDX Map creation is done with TILEd Style of map Isometric Collision Engine? ... well this is where I need a bit of guidance and advice. LibGdx is linked in with Box2d which makes it . I'd personally love to use Box2D, more because I've played around with it on a platform level and I liked how it operated with force and impulses etc, however, it seems to be created for only platform style games. So I guess one questions is Can Box2d's properties be easily changed to support a Top Down collision system or an Isometric collision system? I have tried to implement Box2d into a top down game before by setting the gravity to zero, but with no gravity, the other entities on the map just float. (You bump into them and they just start... floating!) What I was originally thinking was once I have my map created in TILEd, I would start adding a collision layer (Or modify the tiles individually) to mark what is passable and what is not. I have seen examples for box2d (again Platform only however) ways to create an Object in TILEd to mark the collidable wall or floor and when loaded it would create the shapes. Box2d would be perfect if it wasn't for the whole floating entity due to zero gravity. So what I am looking for... 1) Is there a way to create Box2D work on a Top Down set up without entities floating? 2) If not, what other solutions do I have for collision? If there is any other information needed for a better response Please let me know! Thank you!
18
Ball vs 45 degree slope collision detection I have a simple game in which the player moves a ball around. The ball bounces off of walls. Right now I have square walls( ) implemented I use simple bounding box collisions to check if the player will move into a wall when updating its x or y speed and if so, I multiply that speed with 1 to make them bounce. However, I also want to implement triangular pieces( ). To bounce back I believe one can simply use newxspeed 1 yspeed newyspeed 1 xspeed However, what I am having trouble with is the collision detection When does the player hit the diagonal?
18
Player hitting bottom of tile when beside it? So my player checks if it is colliding with tiles, and it works pretty good. However, when the player is against a wall, moving upwards and sideways, it detects it as hitting the bottom of the wall since the player checks for up and down collision first. How do I prevent this? Maybe there is another collision method I could use? Thanks in advance Here's the collision code player.checkCollision function (obj) const top obj.y this.h const bottom obj.y obj.h const left obj.x this.w const right obj.x obj.w if (this.x gt left amp amp this.x lt right) if (this.y gt top amp amp this.y this.vel.y lt top) this.y top this.vel.y 0 return 1 if (this.y lt bottom amp amp this.y this.vel.y gt bottom) this.y bottom this.vel.y 0 return 1 if (this.y gt top amp amp this.y lt bottom) if (this.x gt left amp amp this.x this.vel.x lt left) this.x left this.vel.x 0 return 1 if (this.x lt right amp amp this.x this.vel.x gt right) this.x right this.vel.x 0 return 1 return 0
18
Allowing one sprite to move through another in Quintus I have a Bumper class extended from Sprite Q.Sprite.extend("Bumper", init function(p) this. super(p, gravity 0 ) this.add("2d, ... etc. I have an Enemy class that should trigger a function when the center of the Bumper and of the Enemy collide. I was thinking about doing something like this in my Enemy class this.on("bump.top, bump.bottom, bump.left, bump.right", function(collision) if(collision.obj.isA("Bumper")) if (this.p.x collision.obj.p.x amp amp this.p.y collision.obj.p.y) Do something ) But for that I need the two sprites to move through one another. Is there a way to do that while still checking for collision ?
18
Finding the contact point with SAT The Separating Axis Theorem (SAT) makes it simple to determine the Minimum Translation Vector, i.e., the shortest vector that can separate two colliding objects. However, what I need is the vector that separates the objects along the vector that the penetrating object is moving (i.e. the contact point). I drew a picture to help clarify. There is one box, moving from the before to the after position. In its after position, it intersects the grey polygon. SAT can easily return the MTV, which is the red vector. I am looking to calculate the blue vector. My current solution performs a binary search between the before and after positions until the length of the blue vector is known to a certain threshold. It works but it's a very expensive calculation since the collision between shapes needs to be recalculated every loop. Is there a simpler and or more efficient way to find the contact point vector?
18
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.
18
Find the co ordinates of collided objects in Python I have a group containing my aliens and another containing the bullets I have fired. When I detect their collisions, I want to pull the alien's x y co ordinates during it's deletion so I can put an explosion animation in that location. How do I achieve this? My attempts so far give an error saying group items cannot be indexed. This is my first real coding project so still new. I'm using Pygame to make the game. Current collision detection code def check bullet alien collisions(ai settings,screen,stats,sb,ship,aliens,bullets,bombs) """Respond to bullet alien collisions""" collisions pygame.sprite.groupcollide(bullets,aliens,True,True) Collect X Y co ordinates here if collisions for aliens in collisions.values() stats.score ai settings.alien points len(aliens) sb.prep score() stats.aliens hit 1 stats.calc accuracy() sb.accuracy() check high score(stats,sb)
18
Complex collisions in pygame I've seen many tutorials for simple rectangle or circle based collision detection with pygame. But how can I do more complex collisions with arbitrary polygons? Is the only option pixel based collision detection?
18
How to manage collision between balls in Game Maker 2 (Drag and Drop) Hey there I'm using Game Maker 2 Drag and Drop for a project, I made a game like Break Out and when the ball collides with the wall it doesn't bounce, in Game Maker Studio we had Bounce Action but in GMS2 is deleted, can anyone help me about this issue?
18
LibGDX Colllisions between bullets and enemies in arrays I am writing a "Gauntlet" style game. So far I have managed to successfully detect collisions between my player object and my ghost enemy objects, and when they collide they drain the player's energy. The Ghosts are stored in an ArrayList. I now have bullets which the player can fire, these are instantiated from the Player class and added to another ArrayList called bullets. I typically have around 50 ghosts on the screen dotted around the map. ArrayList lt Ghost gt ghosts new ArrayList lt Ghost gt () ArrayList lt Bullet gt bullets new ArrayList lt Bullet gt () The ghosts and bullets are added to these lists when spawned fired I have tried to implement a method as per below, to try and determine whether a ghost's bounding rect and a bullet's bounding rect overlap, as follows Check if a ghost has been hit by a bullet public void checkGhostsHit() Iterator lt Ghost gt iterEn ghosts.iterator() while ( iterEn.hasNext() ) Ghost g iterEn.next() initialise the bullet iterator each time here Iterator lt Bullet gt iterBul Player.bullets.iterator() while ( iterBul.hasNext() ) Bullet b iterBul.next() if ( b.getBoundingRect().overlaps( g.getBoundingRect() ) ) Gdx.app.log("Enemy", " Hit") iterBul.remove() iterEn.remove() This method is being called from my main render loop but I cannot get it working for love or money. I have tried various forms of the above method, including 'For' loops etc. Am I performing the check in the correct place? Should the Bullet class instance iteself be checking for a collision, or is the above approach the correct idea. As you can tell I'm a noob to this and I am still struggling with working out which activities should be undertaken by particular game Classes.
18
Terrain collision with sphere and OBB I'm implementing my physics engine for my 3D game. So far I've been able to implement collision detection between OBB, spheres and planes. The engine generate contacts and resolve them with an iterative impulse based approach. The result is this (so far). Now I need to detect and generate contacts between a height map terrain and those bounding volumes (sphere and OBB). The terrain looks like this I don't know how to do it. I need to detect collisions and generate contact data (contact point, contact normal and interpenetration to feed my existing engine). I know I can't use a SAT because the terrain in not convex. What about ad hoc code for boxes and spheres? or is there a general approach? EDIT I narrowed down my problem to detecting (and resolving) collisions between a simple convex collidable (sphere OBB) and triangles (always convex). Since the terrain is stored as an height map I can easily select a subset of triangles to run the algorithm against. I can use the SAT to detect interpenetrations. But what about collision response? How can I generate the necessary contact data (collision point and collision normal) to resolve the collision?
18
Calculating Damage from from object collision I need to calculate the damage resulting from a crash of two objects. I found the formula of the resulting kinetic energy E m v 2 I guess I also have to use the masses or sizes of the objects as well. It will make a difference if the spaceship collides with a mountain (which certainly will make both of them dealing heavy damage), or the spaceship is colliding with a floating tennisball in which case neither of them are dealing damage.
18
Libgdx If Rectangle overlaps anything? I've written a code that allows me to talk with an NPC. This works as long as there is only 1 NPC on the map. I'll explain why. public void getNPCCollision() for (int i players.size() 1 i gt 0 i ) Player player players.get(i) for (int j beings.size() 1 j gt 0 j ) Being being beings.get(j) if(player.getBounds().overlaps(being.getBounds())) setX(oldX) velocity.x 0 setY(oldY) velocity.y 0 else if(player.getBounds().overlaps(being.getTalkingBounds())) canTalk true talkAbleBeing being else talkAbleBeing null canTalk false I check every update if my Player walks into an NPC's Talking Rectangle. It goes by every NPC on the map. The thing is If I'm not on NPC 1's rectangle but on NPC 2's rectangle, It'll still set canTalk to False because I'm indeed not in his rectangle. Is there any way I can fix this issue? Please, any help appreciated.
18
How can I get the specific tile in a collision with a Tilemap? I am developing a simple platformer, I have three types of tiles right now Floor does nothing on collision. Bad makes the player lose the game. Good makes the player beat the game. I am trying to detect the collision with this code I found extends RigidBody2D func process(delta) var tile get parent().get node("TileMap").get cellv(get parent().get node("TileMap").world to map(position)) print(tile) The tile variable is supposed to contain the identifier of the type of tile the player is touching, but it doesn't, it always returns 1 (No exception or error, just 1). I believe returning 1 means it isn't touching any tile, but it is. This is using Godot 3.0 stable. What am I missing? Thank you for your patience.
18
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.
18
AABB Collision Detection Confusion I am trying to understand and implement AABB collision to learn simple 2D game physics. I'm following a tutorial and its method is a bit different to other websites. It uses the center of the object and its "half size" to determine collision. This is its code public bool Overlaps(AABB other) if ( Mathf.Abs(center.x other.center.x) gt halfSize.x other.halfSize.x ) return false if ( Mathf.Abs(center.y other.center.y) gt halfSize.y other.halfSize.y ) return false return true And this is the seemingly more popular option if (rect1.x lt rect2.x rect2.width amp amp rect1.x rect1.width gt rect2.x amp amp rect1.y lt rect2.y rect2.height amp amp rect1.y rect1.height gt rect2.y) collision detected! Which one is more efficient? And for the first option, would I define the center and half size like this AABB new AABB(new Vector2(Width 2, Height 2), new Vector2(Width 2, Height 2)) Center and half size method source https gamedevelopment.tutsplus.com tutorials basic 2d platformer physics part 1 cms 25799 Position and width height source https developer.mozilla.org en US docs Games Techniques 2D collision detection
18
Circle inside ellipse collision intersection (preventing circle from leaving the ellipse) I am working on a 2D RPG with a turned based battle system. Characters move inside the confines of an ellipse movement area and when they leave the boundaries will be pushed back inside. (i.e they should be able to walk around the inner part of the ellipse). Previously we were using circles for the movement area and I wrote the code to do circle inside circle collision (not too difficult because the radius is always the same) but since we will change to using an ellipse, I am trying to update the code. I have looked at a few solutions for actual ellipse collision intersection and the math looks..daunting. My questions are Are there any clean solutions to doing circle inside ellipse collision intersection? Should I be approximating the ellipse collision in another way? Like using an n sided polygon? I am a bit lost on how to approach this and could really use some advice.
18
How many and which axes to use for 3D OBB collision with SAT I've been implementing the SAT based on Dynamic Collision Detection using Oriented Bounding Boxes PDF On page 7, in the table, it refers the 15 axis to test so we can find a collision, but with just Ax, Ay and Az, I'm already getting collisions. Why do i need to test all the other cases? Is there any situation where just Ax, Ay and Az are not enough?
18
Best way to traverse triangles in a mesh I'm implementing non projective decals. As described in many places (ie lengyel in the gpg2) I first need to detect all triangles that lie within some sort of frustum. Besides obvious brute force solutions (ie checking each triangle), what are better ways to generally search triangles in a mesh? One solution i can think of is, for each mesh, keep some parallel data structure better suited for searching. are there any well know algo solutions?
18
Detecting a click on a tile I'm making a simple tile map system in LWJGL, and I'm trying to figure out how to detect if the mouse is clicking inside of a tile. So far no matter where I click it's always the same tile that is shown. Code int blockWidth 100 int blockHeight 100 List lt Tile gt tiles new ArrayList lt Tile gt () private void addTiles() for(int i 0 i lt ((Display.getHeight() blockHeight) (Display.getWidth() blockWidth)) i ) tiles.add(new Tile(10,10,blockWidth,blockHeight, i)) ... if(Mouse.isButtonDown(0)) System.out.println("Mouse clicked at (" Mouse.getX() ", " Mouse.getY() ")") for(Tile tile tiles) if(tile.inBounds(Mouse.getX(), Mouse.getY())) tile.highlight() System.out.println("Box clicked at (" Mouse.getX() ", " Mouse.getY() ").") break the inBounds method public boolean inBounds(int x, int y) Rectangle bounds new Rectangle() bounds.setBounds(x, y, width, height) if(bounds.intersects(x,y,1,1)) System.out.println("Tile " num " clicked. X Y val is (" this.x "," this.y ")") return true else return false
18
How to determine which cells in a grid intersect with a given triangle? I'm currently writing a 2D AI simulation, but I'm not completely certain how to check whether the position of an agent is within the field of view of another. Currently, my world partitioning is simple cell space partitioning (a grid). I want to use a triangle to represent the field of view, but how can I calculate the cells that intersect with the triangle? Similar to this picture The red areas are the cells I want to calculate, by checking whether the triangle intersects those cells. Thanks in advance. EDIT Just to add to the confusion (or perhaps even make it easier). Each cell has a min and max vector where the min is the bottom left corner and the max is the top right corner.
18
Dealing with collisions across adjacent static bodies The Problem I have the following setup A, B and C are rectangular static bodies in box2d. p is a circular dynamic body in box2d. The movement of 'p' is solely controlled by the current gravity force of the world. When 'p' collides with a static body (A, B or C) I play a bouncy sound. I handle this through a standard ContactListener. No problems there. The problem arises when 'p' is on 'A' and traveling left towards 'B'. This causes another collision to fire (on 'B') which results in another bouncy sound which is unwanted. If however 'p' was to be traveling right and contacted 'C' I would want the sound to play (given enough velocity, etc). TL DR When sliding across multiple static bodies how do I effectively ignore collisions from a body that is on the same 'line' I'm already on? What I've Tried I've tried numerous different approaches such as on collision tracking that normal as my 'ground' normal and ignoring collisions from the same normal. This works until I do something like make contact with 'C' which then becomes my new 'ground' normal. But having never lost contact with 'A' if I go back towards 'B' I will trigger another collision and we're back to square one. The Plea Looking for code based solutions or ideas if at all possible. I've considered trying something like a chain shape around my level's collidable areas, but with certain parts of my world being dynamic I don't feel like that's an adequate solution. Thanks!
18
How to get distance from point to line with distinction between side of line? I'm making a 2d racing game. I'm taking the nice standard approach of having a set of points defining the center of the track and detecting whether the car is off the track by detecting its distance from the nearest point. The nicest way I've found of doing this is using the formula d Am Bn C sqrt(A 2 B 2) Unfortunately, to have proper collision resolution, I need to know which side of the line the car is hitting, but I can't do that with this formula because it only returns positive numbers. So my question is is there a formula that will give me positive or negative numbers based on which side of the line the point is on? Can I just get rid of the absolute value in the formula or do I need to do something else?
18
How do I handle Isometric collision detection? I would like to make an isometric run jump style platformer. The player should be able to jump on top of platforms above the floor, hit the side of objects etc. I'll be using a 2D game engine so I wouldn't like to emulate full 3D collision for dimensions I'm not using. I'm thinking objects in the game should be placed using X, Y, width, height, and Z for depth. Using those values, how should I detect collisions?
18
What is the MTV (Minimum Translation Vector) in SAT (Seperation of axis)? What is the MTV (Minimum Translation Vector) in SAT (Seperation of axis)? and how can i use it? Im trying to create my first game, where a ball can hit a a static brick (rectangle). Now if a ball collides with a brick, then i need to figure out which side the ball collided with so i can tell the ball which direction it should bounce off to. For example, if a ball is heading nortwest and hitting the brick on its right side, then it should bounce in a northeast direction. however if the ball hit's the bottom side of the brick, then the ball should be heading southwest. So can the MTV be used in this situation? can MTV tell me which side of a rectangle the ball has impacted? Please note i have implemented SAT in my game, and the collision detection works fine, my question now is, can i use MTV to actually handle a collision response? Any help is appreciated.
18
Is an extra collision mesh for level data worth the hassle? What is the optimal approach for collision detection with the environment in an 3D engine (with triangle mesh based geometry, no bsp)? A) Use the render mesh no need for additional work for artists to fiddle with collision detection high detail is harder for physics calculation maybe use collidable flags for materials compute the collision mesh from the render mesh B) Use an additional collision mesh faster more optimal collision detection additional work (either by the artist or by the programmer who has to develop an algorithm to compute it from the render mesh) more memory useage How do AAA title handle this? And what are the indie dev's approaches?
18
Bullet Apply any Transformation to RigidBody? I'm using Bullet for CollisionDetection. I load a scene from a Collada File using Assimp. Let's say I want to give every object in the scene a RigidBody with a box as CollisionShape. Right now I first load the vertices of the object from the file into my Model Object and then store the transformation matrix. After that I create the CollisionShape with the following code btVector3 rigidBodyPos btCollisionShape collisionShape glm vec3 minMax getMinMaxVertexCoords() glm vec3 minCoords minMax 0 The minmum maximum x y z values in the Mesh glm vec3 maxCoords minMax 1 glm vec3 middleSize glm vec3((maxCoords.x minCoords.x) 2, (maxCoords.y minCoords.y) 2, (maxCoords.z minCoords.z) 2) glm vec3 middlePos glm vec3((maxCoords.x minCoords.x) 2, (maxCoords.y minCoords.y) 2, (maxCoords.z minCoords.z) 2) collisionShape new btBoxShape(btVector3(middleSize.x, middleSize.y, middleSize.z)) rigidBodyPos btVector3(middlePos.x, middlePos.y, middlePos.z) Here's a look at my getMinMaxVertexCoords() glm vec3 Model getMinMaxVertexCoords() float maxValue std numeric limits lt float gt max() float minValue std numeric limits lt float gt lowest() glm vec3 lowestVec glm vec3(maxValue, maxValue, maxValue) glm vec3 highestVec glm vec3(minValue, minValue, minValue) for (Vertex v getVertices()) Apply Transform glm vec4 pos getModelMatrix() glm vec4(v.position, 1) glm vec3 homogenizedPos glm vec3(pos.x pos.w, pos.y pos.w, pos.z pos.w) lowestVec.x min(pos.x, lowestVec.x) lowestVec.y min(pos.y, lowestVec.y) lowestVec.z min(pos.z, lowestVec.z) highestVec.x max(pos.x, highestVec.x) highestVec.y max(pos.y, highestVec.y) highestVec.z max(pos.z, highestVec.z) glm vec3 res 2 lowestVec, highestVec return res The problem doing it this way is, if my scene contains a rotated cube, the collisionbox is obviously not rotated, but parallel to the axes. I tried solving this by applying the transformation matrix only after creating the RigidBody (so when creating the CollisionShape the ModelMatrix is the identity matrix) and then transforming the RigidBody afterwards btTransform transform transform.setFromOpenGLMatrix(glm value ptr(getModelMatrix())) rigidBody gt setWorldTransform(transform) The problem with this however is that the box might be rotated now, but if the transformation contains a Scaling which is very likely Bullet does not accept it, and my RigidBody basically disappears (no collision is detected anymore). Does anybody know a solution to this problem?
18
GJK point in tetrahedron capping the number of searches? The very informative mollyrocket video has given me quite a lot to work with, but one thing that the video seems to suggest is that the algorithm should ideally run until it definitely determines whether or not there's a hit. I was of the idea that if there's no collision, it would be obvious by testing the dot product of the latest point against the search direction if it is not positive, then we did not pass the origin, so a tetrahedron which encloses the origin simply cannot be built. In cases where there is a hit OR a clear miss, the routine typically picks up less than 11 loops through. However, as I tend towards 'questionable territory' and the definitive hit miss is visually less distinct, there are times when the method apparently continues to pass the origin yet construct unsuccessful simplexes. Is it common to cap this kind of function at a max number of tries? Right now I am somewhat arbitrarily using the number of points in one shape times the number of points in the other shape in other words max tries len(shape1.pts) len(shape2.pts) It feels a bit hacky and I have to assume that the routine is geared towards simply running ad nauseum until it smacks into a clear hit miss situation. Has anyone experienced this before? Is this a problem or an anticipated safety measure in such an algorithm? If it needs to be done I'll gladly share some code, but I think it stands as self evident that it is kind of a longer read than most code snippets so I've abstained for now.
18
Does collision detection data structures require a manifold mesh Is it possible to apply spatial split techniques (oct trees bsp trees, etc) when meshes are not necessary manifolds? The mesh in question represents the "map". This means that it is static so spatial splits should be a good approach. Not requiring a manifold saves a lot of time when modeling, and also it may reduce the number of extra faces that has to be drawn, as forcing the mesh to be a manifold may require additional cuts.
18
How to implement collision detection of portals? For example, take this scenario (excuse my horrible drawing skills) This is based on "Portal", where the stickman is going through the blue portal (which is linked to the red portal), but there is a wall stopping him on the red portal. Therefore he cannot go completely through the portal. So my question is this How do I do the physics collision detection with them? Do I slice the player? Is there a way to link them? Are there any physics engines that support doing this? If not, how would I make one?
18
Calculating the intersection of a fast moving circle and a line Inside of my game, I am in need of a way to test the collision between a line segment and a fast moving circle. I would say I need a line v capsule collision however the problem is I need the collision point. None of the existing formulas I can find can do quite what I need. I have tried line x line intersection and just moving the lines by the radius of the capsule sort of work however then the collision point found around the edges is off. Additionally, I can't find a way to work back from the collision point to the point that the circle first collided at. Above is sort of a picture of what I am hoping to achieve. The green capsule represents the circle's path. So really the problem here is finding that collision point because a yes or no answer is trivial here. There are formulas for ray capsule or box capsule however none of them will get me this collision point. Does anyone have any ideas on how I can figure this out?
18
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.
18
Avoid shaking artifacts in 3D continuous collision detection I am programming a 3D game physics engine that uses continuous collision detection to avoid my objects from being able to "tunnel" through the geometry. Here is basically how it works Execute a swept object world collision check Move the object up to the exact point where it collides If no time is remaining, everything is done, just stop Else, update the velocity so that the object "slides" in a direction orthogonal to the collision normal before returning to step 1. This is the formula I use for this sliding (I just remove the component of the motion in the normal direction) velocity velocity (velocity dot normal) normal My problem occurs in this kind of situation (Do not take into account faces other than A and B, their only purpose is the emphasize the 3D aspect of the shape) In the first frame, the object first follows the black arrow, then collides face A. It slides correctly on face A (first red arrow) and then climbs on face B (second red arrow). The problem with this algorithm is precisely the fact that it can climb on the opposite face after several consecutive frames (here the other frames are the cyan and green ones), the general motion will follow the good path (the intersection line of planes A and B), but with a local left right shaking artifact that I would appreciate getting rid of. Any idea to solve this would be greatly appreciated.
18
FPS Collision detection and movement How is collision detection and movement typically handled in a FPS, particularly handling slight changes in ground height such as stairs (both on incline and decline)?
18
Collision Detection For A Maze Cave I have a simple code written in Processing 3.x that I am using to test out the collision detection for a cave maze. The code is here https github.com NoahJon3s New Journey The Game blob master sketch 190820a.pde If you where to run said code, you'd see that I have the code so that it detects collisions on the x axis (top of the rectangle) and y axis (left side of the rectangle), and correctly prevents the movement of the "player" from moving out of the rectangle, but I cannot seem to find a solution for preventing the movement out of the bottom or the right side of the rectangle, even though I am able to detect the collision. Every solution I try seems to lock the "player" to those respective sides. Any suggestions? Thanks in advance.
18
Most efficient way to check collision For example, I have a player and a map, to check player collision with some block we need to check entire map tiles, but the bigger the map, the slower the framerate. What's most efficient way to check collision?
18
Rendering after interpolating, renders inside outside other objects So, we're working out our interpolated render coordinates during our render call and it's doing a fantastic job of smoothing everything out. All is great and collision detection is working to a perfectly acceptable level (for simple CD ie, player hits other object, looses a life, starts over...). However, how do we deal with situations that require 'collision and resolution'? The classic example, of course, being our player character colliding with a solid object (usually a platform or the ground) and then being 'resolved' to bring the 2 entities out of collision.... here is what I mean Even if we say something simple like 'just don't interpolate vertically when touching a platform' that wouldn't seem a very clean solution because we need to think about slopes where the player is moving both left right as well as up down. What is the easiest and cleanest way to protect ourselves from this happening?
18
Best collision shape for rooms I'm wondering what is the most efficient collision shape to use with APIs like Bullet or Havok for rooms interiors. Rooms tend to be boxes but are concave since the normals point inward which means no to the box shape. Rooms also can have holes in the walls (doors, windows, etc) too. If I'm assigning shapes with a modeling tool like Blender it seems like my only option is a Triangle Mesh shape but it seems like I should be able to get away with a cheaper (performance wise) shape for something like this.
18
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.
18
Sweep and Prune vs Quad Tree I need some broad phase algorithm for my 2d game (shmup, bullet hell). Does one or another solution have any major advantages?
18
Dealing with collisions across adjacent static bodies The Problem I have the following setup A, B and C are rectangular static bodies in box2d. p is a circular dynamic body in box2d. The movement of 'p' is solely controlled by the current gravity force of the world. When 'p' collides with a static body (A, B or C) I play a bouncy sound. I handle this through a standard ContactListener. No problems there. The problem arises when 'p' is on 'A' and traveling left towards 'B'. This causes another collision to fire (on 'B') which results in another bouncy sound which is unwanted. If however 'p' was to be traveling right and contacted 'C' I would want the sound to play (given enough velocity, etc). TL DR When sliding across multiple static bodies how do I effectively ignore collisions from a body that is on the same 'line' I'm already on? What I've Tried I've tried numerous different approaches such as on collision tracking that normal as my 'ground' normal and ignoring collisions from the same normal. This works until I do something like make contact with 'C' which then becomes my new 'ground' normal. But having never lost contact with 'A' if I go back towards 'B' I will trigger another collision and we're back to square one. The Plea Looking for code based solutions or ideas if at all possible. I've considered trying something like a chain shape around my level's collidable areas, but with certain parts of my world being dynamic I don't feel like that's an adequate solution. Thanks!
18
Circle inside ellipse collision intersection (preventing circle from leaving the ellipse) I am working on a 2D RPG with a turned based battle system. Characters move inside the confines of an ellipse movement area and when they leave the boundaries will be pushed back inside. (i.e they should be able to walk around the inner part of the ellipse). Previously we were using circles for the movement area and I wrote the code to do circle inside circle collision (not too difficult because the radius is always the same) but since we will change to using an ellipse, I am trying to update the code. I have looked at a few solutions for actual ellipse collision intersection and the math looks..daunting. My questions are Are there any clean solutions to doing circle inside ellipse collision intersection? Should I be approximating the ellipse collision in another way? Like using an n sided polygon? I am a bit lost on how to approach this and could really use some advice.
18
How do I implement pixel exact collision server side? Recently I made a 2D offline game with HTML5 Canvas and JavaScript. I'm detecting collisions by first checking whether image bounding boxes overlap. If they do, I check against the bounding boxes, to see if there are any pixels that exist in the same location for both images. I learned the technique from this tutorial (YouTube). Now I'm making a multi player version of the game, in a client server configuration. I've decided to have the server handle all physics, including collision. However, I'm not sure how to implement that. Since the images are drawn client side, the server cannot access image's data to do the pixel collision tests. I can make bounding boxes on the server side, but how do I detect pixel collisions? Tech details I intend to write the server in node.js, using either CouchDB or MongoDB as my database.
18
body entered signal won't emit when rigidbody collided to rigidbody I have multiple rigidbody object floating away in the space. When they hit each other, they push away each. I want to destroy object if they hit something, but connect body entered signal won't invoked when they impact each other func ready() connect("body entered", self, "destroy") func destroy(body) print("HIT!") queue free() How do I check Rigidbody hit something?
18
How do I make good guy attacks only hit bad guys and vice versa? My game has many different type of good guys and many different type of bad guys. They will all be firing projectiles at each other but I don't want any accidental collateral damage to occur for either alignment. So bad guys should not be able to hit damage other bad guys and good guys should not be able to hit damage other good guys. The way I'm thinking of solving this is by making it so that the Unit instance (this is javascript, btw), has an alignment property that can be either good or bad. And I'll only let collision happen if the class Attack boolean didAttackCollideWithTarget(target) return attack.source.alignment ! target.alignment and collisionDetected(attack.source, target) This is pseudo code, of course. But I'm asking this question because I get the sense that there might be a much more elegant way to design this besides adding yet another property to my Unit class.
18
Project collision shapes to plane for 2.5D collision detection I am working on a top down 2.5D game. In the game anything that overlaps on the screen should be 'colliding' with each other regardless of whether they are on the same plane in the 3D world. This is illustrated below from a side ways view The orange and green circles are spheres floating in the 3D world. They are projected onto a plane parallel to the viewport plane (y 0 in the image) and if they overlap there is a collision event between them. These spheres are attached to other meshes to represent the sphere bounding boxes for collisions. The way I plan to implement this at the moment is the following Get the 3D world position at the center of the sphere. Use Camera.WorldToViewportPoint to project the point to the viewport plane. Move a Sphere Collider with the radius of the sphere to that point. Test for collisions using unity colliders. My question is how to extend this to work for rotated cuboids. For instance if I have two rotated cuboids, if I follow the logic above it would not work as intended as the cuboids may not collide but they could still be intersected on the view plane. An example is below In the example above the cuboids are overlapping from the view of the player, but not colliding when they should be. Is there a way to project a cuboid that would be aligned with the plane? Would it be a valid cuboid for all rotations if I did this? EDIT Corrected the images, before they were incorrectly projecting onto the y 0 plane at 0 rotation, not the plane parallel to the viewport plane.
18
Points on lines where the two lines are the closest together I'm trying to find the points on two lines where the two lines are the closest. I've implemented the following method (Points and Vectors are as you'd expect, and a Line consists of a Point on the line and a non normalized direction Vector from that point) void CDClosestPointsOnTwoLines(Line line1, Line line2, Point closestPoints) closestPoints 0 line1.pointOnLine closestPoints 1 line2.pointOnLine Vector d1 line1.direction Vector d2 line2.direction float a d1.dot(d1) float b d1.dot(d2) float e d2.dot(d2) float d a e b b if (d ! 0) If the two lines are not parallel. Vector r Vector(line1.pointOnLine) Vector(line2.pointOnLine) float c d1.dot(r) float f d2.dot(r) float s (b f c e) d float t (a f b c) d closestPoints 0 line1.positionOnLine(s) closestPoints 1 line2.positionOnLine(t) else printf("Lines were parallel. n") I'm using OpenGL to draw three lines that move around the world, the third of which should be the line that most closely connects the other two lines, the two end points of which are calculated using this function. The problem is that the first point of closestPoints after this function is called will lie on line1, but the second point won't lie on line2, let alone at the closest point on line2! I've checked over the function many times but I can't see where the mistake in my implementation is. I've checked my dot product function, scalar multiplication, subtraction, positionOnLine() etc. etc. So my assumption is that the problem is within this method implementation. If it helps to find the answer, this is function supposed to be an implementation of section 5.1.8 from 'Real Time Collision Detection' by Christer Ericson. Many thanks for any help!
18
In a collision detection loop, when do I apply the velocity? I'm writing a really basic collision detection system (AABB vs AABB, AABB vs Circle, Circle vs Circle), and I've just got to the point of writing the actual loop which iterates the objects and checks for collisions. My question is when do I apply the velocity to each object? Do I move all objects by vel dt before I even start colliding? Do I apply the velocity as I iterate? If so, do I apply it to both objects I'm testing, or just the first, and then apply the velocity to the second when I check collisions against that one? Also presumably I should do the whole collision check recursively (as the act of responding to one collision might cause another), but that obviously effects how and when the velocity is applied. My suspicion is that I should move all the objects by their velocity before I begin, and then recursively detect and respond to collisions until nothing is colliding (or until some loop limit).
18
Libgdx detect when player is outside of screen Im trying to learn libGDX (coming from XNA MonoDevelop), and I'm making a super simple test game to get to know it better. I was wondering how to detect if the player sprite is outside of the screen and make it so it is impossible to go outside of the screen edges. In XNA you could do something like this Prevent player from moving off the left edge of the screen if (player.Position.X lt 0) player.Position new Vector2(0, player.Position.Y) How is this achieved in libgdx? I think it's the Stage that handles the 2D viewport in libgdx? This is my code so far private Texture texture private SpriteBatch batch private Sprite sprite Override public void create () float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() batch new SpriteBatch() texture new Texture(Gdx.files.internal("player.png")) sprite new Sprite(texture) sprite.setPosition(w 2 sprite.getWidth() 2, h 2 sprite.getHeight() 2) Override public void render () Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL LEFT)) sprite.translateX( 1f) else sprite.translateX( 10.0f) if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL LEFT)) sprite.translateX(1f) else sprite.translateX(10f) batch.begin() sprite.draw(batch) batch.end()
18
2D Collision detection and design So, listening to this very smart piece of advice, I've already completed a basic Tetris game. Moving on, I started a small breakout. But suddenly a nightmare came. Collisions. Since I've been struggling with this a lot, I read a bunch of article of the web. Being a beginner, I thought that, in the first approach, I would only use Rectangle to detect collisions. Right. Now I still have some problems. First of all, all the articles I stumbled upon on the Internet told me how to detect collisions, e.g. checking if objects A and B collided with each other. But it is not what I really need. In order to respond properly, I need to tell my objects if the collision happened on the X or Y axis and then setting the new velocity according to some rules. The problem is that there are so many possibilities when making the distinction between types of collisions that I don't think I've taken the right path. The second point (which, I believe, is really tied with the first) is the pattern in which the detection and the resolution of a collision happen. Right now, I have a CollidableObject classes and a CollisionDetector classes which knows about these objects. Each frame, the detector is looking for collision (or at least for me, is trying) and when he finds one, it alerts each collided object, saying "Hey you ! You've have collided with Z on the X axis, change that velocity now." and the object abides. The main issue right now is that I can detect the collision axis and therefore, when saying "Hey you ! You collided !", I cannot respond properly. In which direction should my velocity change ? I've been thinking a lot about this lately, trying to figure it out on my own, but I haven't find something that I liked so I am asking here now. Thank you for your answers ! (Note I don't know if this is relevant, but I'm coding in C using SDL)
18
Cannot decide between using a MessageBus and entities for events in my ECS game For example, let's say that the player walks into an enemy and in response, a chain of events should occur (such as his score goes up, the enemy dies, a cinematic starts, etc.) I see two quot proper quot ways of accomplishing this Method 1 There exists a global message bus in the game. Any system can emit events to it, and any other system can listen for some events from it. For example, the system handling the players score would look like this messageBus.listen( quot playerhitsenemy quot , e gt score e.monsterType ) and the collision system may look like this messageBus.emit( quot playerhitsenemy quot , monsterType 5 ) Similarly, other systems can listen for the same event, such that when something happens, the CPU immediately moves from processing the current system to the other system processing this event. That is, the emit call is basically just a list of callbacks that are immediately invoked and sent the message. Method 2 The second method, instead, is to encode events messages as entities themselves. That is, when an event occurs (such as the player hitting something in the collision detection system), this would happen let newEntity new Entity() newEntity.components.push(new MessageComponent()) newEntity.components.push(new MessagePlayerHitsEnemyComponent(5)) entityAdmin.spawnNewEntitiy(newEntity) That is, a new quot message quot entity is created, and it is given the generic Message component and the concrete event component type as well, MessagePlayerHitsEnemy. Then, all systems interested in these messages would have something like this in their execute function for (let entity of entityAdmin.query(MessagePlayerHitsEnemyComponent) let monsterType entity.getComponent lt MessagePlayerHitsEnemyComponent gt () score monsterType And then at the end of the frame there would be a system whose responsibility was deleting all messages, like so for (let entity of entityAdmin.query(MessageComponent) entityAdmin.remove(entity) I cannot decide which is better. The first method seems simpler and probably more efficient in Javascript, considering it's just immediately invoking all the requested functions. However, the second one seems more quot correct quot , in each system is iteratively processed. That is, first the collision system runs in its entirety, then the scoring system, etc. There is no quot jumping around quot from system to system during execution. Each system processes everything in its entirety, and then the second system processes everything it's interested in, etc. So, in essence, the first method seems simpler and more efficient, while the latter method seems more quot correct quot , pure, verbose, debuggable, and extendable. Which one should I pick?
18
How to store 3D entity position, offset, and transformation data for parent and children? I am looking for a cleaner pattern to storing character position data, offsets, and transformations. I currently have a character with a vec3 for position. Entity position vec3 rotation vec4Quaternion velocity vec3 I use this position vector as the world coordinate. So that when Y 0 I imagine the characters feet are on the ground. This makes it easier to think about where the entity is in world space. The problem I am having is that mesh entities like colliders or the skin mesh will assume a position vector at the center of the mesh. This is causing me to have to do a bunch of transformation juggling. I can't 1 to 1 map these meshes to the entities world position. I will update my characters 'ground position' when they move. then have to calculate the new 'center position' which is calculated like centerPosition groundPosition.x groundPosition.y entityHeight 2, groundPosition.z I"m wondering if there is a better pattern for this. Maybe I assume the entities position vector is a 'center position' as well? but not clear to me how to handle the ground offset in that case.
18
What's the fastest way checking if two moving AABBs intersect? I have two AABBs that are moving, what's the fastest way to check if they will intersect under a frame? By moving I mean not just to check with the usual rectangle intersection method, I mean some kind of simple easy swept test that only returns a boolean, no hit time or anything else. What I think is to simply do it like this But that Hexagon is quite complex and I don't know how to calculate an AABB Polygon intersection, is there maybe an easier way? Any programming language that you like the most, I can easily port it. Thanks.
18
Find the Contact Normal of Rectangle Collision It seems a lot of people have asked similar questions on this site, and every time it seems like a whole bunch of answers that don't work are given. Basically, I have two rectangles (AABBs) that collide, and I want to find out on what side they collided with each other. I know the velocities of each object before they collide, and of course their positions before and when they've actually collided (if I use discrete collision checking that is, currently I'm using speculative). Many people say find the lowest penetration distance or take the largest speed (either horizontal or vertical) and that will give you the answer. But the collision is dependent on both of those values, I just don't know how they fit together to tell me where the collision is coming from. I don't think I need an exception for corner collisions. I do not want to do my horizontal and vertical collisions separately as that just opens up even more problems. So, any suggestions?
18
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
18
Proper Angled Top Down Wall Collision? Sorry about the vague title, it's kind of hard to say what I want to do in a few words. In my top down game, I'm having a problem implementing proper collision for walls facing north (that is, you can actually see the surface of the wall, as opposed to the other directions, where you can see just the top). I have a proper bounding box that detects the alpha values of the sprite, and generates a proper bounding box around only the visible pixels, like so http a.pomf.se kfrxtm.mp4 However, when dealing with walls, I run into a problem. With my current implementation, there are two options I have Set the walls so that the player can pass through them. This leads to the player walking "on" the walls, like so Set the walls so that the player can not pass through them. This leads to the player's head colliding on the bottom of the wall, like so In the image, the player can not move forward any more. My solution to this, would be to place the bounding box around the player's feet. However, this would interfere with my alpha based system, and other collision systems (enemies hitting the player, etc.) How should I approach this? If my question is unclear, I can provide more images and descriptions of what I'm trying to achieve.
18
Where in code to for collision? In object class? Mainline code? Making a simple game in Love 2D framework where if I click on an object then it disappears. Do I check to see if I've clicked the enemy inside a function in the enemy object? Or just in my main.lua? Currently I have this code in my main.lua function love.mousepressed(x, y, button) if button "l" then for i,b in ipairs(bugs) do if b isClicked(x, y) then table.remove(bugs, i) end end end end Is there a standard design pattern on where this code should belong?