How do I make circles bounce off each other realistically? I'm trying to create bouncing balls with realistic physics. At the moment, when the balls hit each other, they bounce back in the same direction they came from. How do I make them more realistic? I don't know much about physics. What things should I be reading about? Here's an image of how I imagine balls would bounce in real life how I think it should work (original source http thewombatguru.nl Bouncing.png) Is this how it works?


Issue with removing sprites on collision I'm trying to make a very simple collision detection procedure just for test purposes. The problem is with the send receive information between functions I have these lines on the update method (could be later implemented for checking what kind of subclass node is) CCSprite sprite background spriteCollisionWithRect player.boundingBox if (sprite! nil) sprite removeFromParentAndCleanup YES and this is the spriteCollisionWithRect method (CCSprite )spriteCollisionWithRect (CGRect)bounds for (CCSprite sprite in spritesArray) if (CGRectIntersectsRect(sprite.boundingBox, bounds)) return sprite return nil Now, this way not all the sprites are removed. It only works occasionally. But if I remove the node inside the collision method instead of returning it, it works nicely. (CCSprite )spriteCollisionWithRect (CGRect)bounds for (CCSprite sprite in spritesArray) if (CGRectIntersectsRect(sprite.boundingBox, bounds)) sprite removeFromParentAndCleanup YES return nil Why is this?


How do you set multiple collision rules with Swift and SpriteKit? So basically I've got 2 types of balls and 2 types of enemies. Green can delete red only, red can hit delete only. Here's what I have for the first collision test func didBeginContact(contact SKPhysicsContact) 1. Create local variables for two physics bodies var firstBody SKPhysicsBody var secondBody SKPhysicsBody 2. Assign the two physics bodies so that the one with the lower category is always stored in firstBody if contact.bodyA.categoryBitMask lt contact.bodyB.categoryBitMask firstBody contact.bodyA secondBody contact.bodyB else firstBody contact.bodyB secondBody contact.bodyA 3. react to the contact between ball and bottom if firstBody.categoryBitMask RedBallCategory amp amp secondBody.categoryBitMask GreenBarCategory (secondBody.node!.removeFromParent()) score scoreLabel.text " (score)" This works as expected, red ball hits the green bar and it deletes him. You can't just make a func didBeginContact 2 and change the bit masks as far as I'm aware..or at least it didn't work when I tried it, so how do you handle multiple rules for collision? All of the basic tutorials I've seen handle something like one bullet hitting one type of enemy. What if you have 2 "bullets" and 2 enemies?


How can I make player object collide and keep moving until it is as close as possible to click location? I am making a basic point and click adventure game. I can make the player object move towards the location of a mouse click and collide with walls, but movement stops the instant a collision occurs. I would like the player object to keep moving (slide along the wall) and get as close as it can to the mouse click location, without passing through a wall of course. I have Create, Step, Collision amp Global Mouse click events. Please see below for code and diagrams. Any help will be much appreciated. Create Event code stop player moving on create enum mouse none xx mouse.none yy mouse.none player move speed 2 init collision speed player move speed 1 Step Event code general keys if keyboard check pressed(vk escape) game end() point and click movement if (xx ! mouse.none and yy ! mouse.none) move towards point(xx,yy,player move speed) else speed 0 if (distance to point(xx,yy) lt collision speed) xx mouse.none yy mouse.none Global Left Pressed code xx mouse x yy mouse y


Detecting a Collision Between Two Bodies Undergoing Multiple Transformations I have been searching for an answer to this for a really long time and I have not found any definitive answers as of yet. What I am trying to do is determine if and when two bodies collided between the times t0 and t1. Calculating this is much more straight forward if each body is only either translating or rotating (about center or any point), but when adding multiple transformations on top of each other, things become a bit more messy. I made this animation to illustrate the problem. As you can see, at times t0 and t1 there are no collisions, but between there are multiple collisions occurring. One way I thought of for tackling this problem was to reduce the size of the time intervals. So, between t0 and t1 there would be a total of n updates to check for collisions. This works, but the only way I found that I could guarantee no false negatives, i.e. not finding a collision that happened, was to integrate over extremely small time steps. As you can imagine, this is very costly because it resulted in the tens to hundreds of time steps per body per update cycle. I am not saying this idea has no merit (it makes calculating the collision response much easier since I know the exact points of contact), but I would need to find a way to calculate the minimum number of time steps rather than uniformly moving each body forward one unit of distance rotation until they reach the desired position and orientation. So, my question is two parts Is there a better way of determining if and when a collision occurs? If not, is it possible to calculate the minimum number of time steps? P.S. I think the maximum translation per time step can be the shortest distance between any two points in the body. This would not allow it to hop over anything. When it comes to rotation about the center or orbiting a point I do not know how to determine the minimum angle. It probably has to do with the arc length, but what should that maximum distance be? EDIT this is not right. For a triangle, the base would be the shortest distance between two of its points, but the top could pass through something that is less wide than the triangle base.


SAT Collisions Resolving rotations Currently I have a working 2D SAT collision system with only boxes, but works with static rotations as well, leaving room for triangles. One of the issues I've been able to resolve was tunnelling, thanks to this thread's psuedocode that I got working for myself. Problem is, this doesn't support moving rotations like a system using a minimum translation vector. If I rotate alongside the side of an object, the system will fail even if I'm not moving. My first thought in solving this was to use the longest line you can draw in a square (that being the points on either side of a square) and comparing the length of that to whatever side on any axis, but even squares have different sizes on any given rotation projected onto an axis. The system also doesn't work with multiple objects, because while you can use the algorithm on a group of objects and find the shortest distance out of all of them if I conserve my velocity relative to the colliding axis, diving into the crest of 2 objects means I will phase through one of them not beyond a 45 degree angle. Is there an effective way to resolve collisions on rotations and groups of objects, while using this anti tunnelling algorithm? I don't care if it's expensive, I'll take whatever you can think of.


Finding the Distance between 2 Objects I have 2 objects One Having a Transformation Matrix T1 and other Having Transformation Matrix T2. And We are having a View Matrix V and Projection Matrix P. Basically 2 Object are render using this function Render(vec3 position,X Rotation , Y Rotation, Z Rotation, Scaling) So i am having 2 different T1 and T2 transformation matrix. How should i find the distance between these 2 objects ? Please Explain ? I have tried by simple formula using position vector but it is giving me incorrect distance ?


Bitmap Object Collision Help Is it possible to detect when an object and a bitmap collide. I have an arraylist of sprites that I am shooting with an image. I tried using this method here but as soon as the bitmap appears the sprite disappears, this is in the Sprite class public boolean isCollision(Bitmap other) if(other.getWidth() gt x amp amp other.getWidth() lt x width amp amp gt other.getHeight() gt y amp amp other.getHeight() lt y height) return true


What are the disadvantages of R Trees in collision detection? I was poking around in SQLite and discovered R trees. A little digging revealed that R trees are really just fancy AABB trees. Then I realize that the state of the art in collision detection (often a perf limiting sub system for physics simulation) is dynamic trees (simple AABB trees). So this is indicating to me that we can produce more efficient physics with this as a drop in replacement. Here is a pretty convincing argument for R trees from half a decade ago. To really distill it to the core, R trees were developed for databases to optimize disk access where getting the right data into RAM is the happy place, and now we can recycle the technique to optimize memory access where keeping the right data in cache is the happy place. Sadly it seems that this has not caught on. I wonder what the reasons are? I also found no reference to this BVH method in my Real Time Collision Detection (Ericson) text (though, that book is a bit older than 2010).


Explain Reciprocal Velocity Objects to me This is follow up on this question (Unit collision avoidance for RTS) I'm developing an RTS. I'm having difficulty with collision detection... I looked up RVO and it seems like the correct solution, but I'm having difficulty understanding how it exactly works. Can someone explain the math behind RVO in comprehensible terms? I tried compiling the RVO sample program but it won't compile in the latest version of Visual Studio. I'm stumped.


Collision detection of player larger than clipping tile I want to know how to check for collisions efficiently in case where the player's box is larger than a map tile. On the left is my usual case where I make 8 checks against every surrounding tile, but with the right one it would be much more inefficient. (picture of two cases on the left is the simple case, on the right is the one I need help with) How should I handle the right case?


Detect obstacles in path on a tile based map I'm creating a 2d game with a tile based map, but smooth movement. I currently use A in combination with some other tricks for pathfinding, and one issue what I've been dealing with is getting the units to move smoothly despite tile based pathfinding. My solution at the moment is the use raycasting to determine if there is an obstacle between a unit and its target. If there is, it uses A . Otherwise, it just sets its next move directly as the coordinates of its target. In the case that it uses A , I also use raycasting to determine which point in the path the unit should move to next, by finding the nearest point in the path that is not obstructed from the units current location, and setting that as the next move. This is necessary so the unit doesn't have to move in a jerky fashion based on the tile based path that the A found. Raycasting is faster than A every time, but it still has some overhead with a large number of units since it checks every point on the line in small increments. (More so since I'm doing double raycasting each time to account for the size bounds of the unit) My question is Is there a better algorithm than raycasting to determine if there is an obstacle between two points (independent of the tiles structure) on a tile based map? My thought is that there is some way to take advantage of the tiled nature of the map.


How to go about an intermediate collision resolution system? I would like to know a better way of collision resolution than I am currently doing. My current collision system stores the current positions and previous positions of each object. When an object collides with another it sets the current positions to the previous positions. This would work fine if objects could only move in four directions, but when they can move in more than four directions the system doesn't work. For example if you are moving an object A up and right and it collides with and object B above it, the object A stops moving even if still going up and right. In most 2d games however if this scenario happened the object A would stop moving up but continue to move right. This is the kind of collision resolution that I would like to implement. I don't need anymore complicated physics right now this will do. I'm just using rectangles so that would be the only shape I need to worry about.


What maths should I learn for game programming, and what aspect of programming does it relate to? Possible Duplicate What math should all game programmers know? Obviously a good knowledge of maths is essential for good programming, my maths isn t the best ( I didn t pay attention in school all those years ago) so, in order to get one step closer to being the best I need some advice. What maths should I learn for specific areas of game programming? If someone could outline some subjects and say one or two words about what areas of game programming they would be used in I d greatly appreciate it. I m working through the Khan academy programme at the moment, and I m just getting into algebra now.


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.


Using Lazer with a Quadtree I have a quadtree implementation that works well with what I need for handling collisions between enemies, projectiles, and heroes. However, most of these types of entities are pointbased, with varying radius but that's about it. I have a weapon idea for lazer or ray weapon that's essentially a line. How does something like that fit in to working with something like a quadtree? Normally when we have a quadtree, we are essentially letting that data structure handle point masses to figure out which subset of objects we need. How then might we handle something like a line? The dumb way to do it is to just query the enemies and do something like a circle line intersection test on all the enemy objects. This is obviously not efficient especially when we already have a quadtree. One idea i have are to just put some dummy projectile object along the line and submit those to the quadtree. Then if we get any returned objects from those dummies, then we can use the circle line intersection test on it. Any ideas pertaining to how to use ray weapon that requires some line intersection test with a quadtree would be appreciated. Thanks.


How do I find at least the closest penetrating point with SAT? For more accurate simulations, I want to find the closest point of another polygon to one polygon's center when they collide. Is this possible with the SAT algorithm? Is it a good strategy at all for semi accurate physics simulations (more accurate than the normal between the 2 polygons' centers)?


Box 2d and really complex big shapes I intended to use jbox2d for my project. But as I went deeper into it's manual I'd found out that it supports dynamic objects between 0.1 and 10 meters (if use scaling and assume that 0.1 is smallest unit we would have 100 units). I want to create pretty complex and big shapes about 1000 units width. So will box2d will handle it? Or I should simplify them more to achieve 100 units width max? Or my calculations about 100 units width max are wrong? ( But if 0.1 meter is box2d minimum I don't think than I can get smaller unit as measure.) I had also read about kollider2d, but can't find any info about stress testing it. As in comment below I understand that it doesn't matter if 32 pixels of my system represents 0.1 meter of box2d system nor if it is 50 pixels. With good scale I can manage any value as minimum. I wan't to create objects 1000 times larger than smallest one. And I don't know if box2d will crash or try to handle it but will be very slow or inaccurate.


Is there a way to increase the collision check efficiency of a system of n objects? I'm making a game that consists of many onscreen objects, one of which is the player. I need to know which objects are colliding every iteration. I made something like this for (o in objects) o.stuff() for (other in objects) if (collision(o, other)) doStuff() bla.draw() This has O(n 2), which I'm told is bad. How do I do this more efficiently, is it even possible? I'm doing this in Javascript, and n will usually be lower than 30, will it be a problem if this stays the same?


Collision Avoidance Steering around moving obstacles I've done a decent amount of research and I've read up on pathfinding algorithms and such, but I can't seem to find anything to do with the mentioned behaviors when moving around obstacles that also move. My character has a circular hitbox, as do the obstacles. My character has a fixed velocity, but can also come to a full stop. My character can also change directions near instantly. Acceleration deceleration of my character is instant. I can predict, with 100 accuracy, where the obstacles will be I know their velocity, starting position, and ending position. Obstacles are generated by the user, move at a predetermined velocity (depending on which obstacle it is), and have a predetermined length (again, depending on the obstacle). I want my character to path from point A to point B while moving around all the obstacles (with no collisions). Point A is where my character currently is, and point B is a user picked point which might change at any time (edit Pathfinding itself isn't the issue it's just local collision avoidance that I need to deal with). Let me know if you need any more info I don't know what is needed!


How to Detect Collision Between Entity and Viewport I am using Crafty.js. I want the player to die when they hit the side of the viewport (they need to keep moving to stay alive). How do I detect a collision between the player entity and the side edge of the viewport? I have looked at Crafty.viewport, but have not been able to find anything useful.


Collision in PyGame for spinning rectangular object.touching circles I'm creating a variation of Pong. One of the differences is that I use a rectangular structure as the object which is being bounced around, and I use circles as paddles. So far, all the collision handling I've worked with was using simple math (I wasn't using the collision "feature" in PyGame). The game is contained within a 2 dimensional continuous space. The idea is that the rectangular structure will spin at different speed depending on how far from the center you touch it with the circle. Also, any extremity of the rectangular structure should be able to touch any extremity of the circle. So I need to keep track of where it has been touched on both the circle and the rectangle to figure out the direction it will be bounced to. I intend to have basically 8 possible directions (Up, down, left, right and the half points between each one of those). I can work out the calculation of how the objected will be dislocated once I get the direction it will be dislocated to based on where it has been touch. I also need to keep track of where it has been touched to decide if the rectangular structure will spin clockwise or counter clockwise after it collided. Before I started coding, I read the resources available at the PyGame website on the collision class they have (And its respective functions). I tried to work out the logic of what I was trying to achieve based on those resources and how the game will function. The only thing I could figure out that I could do was to make each one of these objects as a group of rectangular objects, and depending on which rectangle was touched the other would behave accordingly and give the illusion it is a single object. However, not only I don't know if this will work, but I also don't know if it is gonna look convincing based on how PyGame redraws the objects. Is there a way I can use PyGame to handle these collision detections by still having a single object? Can I figure out the point of collision on both objects using functions within PyGame precisely enough to achieve what I'm looking for? P.s I hope the question was specific and clear enough. I apologize if there were any grammar mistakes, English is not my native language.


Collision detection with non rectangular images I'm creating a game and I need to detect collisions between a character and some parts of the environment. Since my character's frames are taken from a sprite sheet with a transparent background, I'm wondering how I should go about detecting collisions between a wall and my character only if the colliding parts are non transparent in both images. I thought about checking only if part of the rectangle the character is in touches the rectangle a tile is in and comparing the alpha channels, but then I have another choice to make... Either I test every single pixel against every single pixel in the other image and if one is true, I detect a collision. That would be terribly ineficient. The other option would be to keep a x,y position of the leftmost, rightmost, etc. non transparent pixel of each image and compare those instead. The problem with this one might be that, for instance, the character's hand could be above a tile (so it would be in a transparent zone of the tile) but a pixel that is not the rightmost could touch part of the tile without being detected. Another problem would be that in different frames, the rightmost, leftmost, etc. pixels might not be at the same position. Should I not bother with that and just check the collisions on the rectangles? It would be simpler, but I'm afraid people.will feel that there are collisions sometimes that shouldn't happen.


How to make a cylindrical collider for a cylindrical mesh in UE4 When I am importing Axis Alligend cylindrical mesh in UE4 here is what I get as an automatically generated collider But if I rotate the mesh in Maya and again exprot FBX to improt in UE4 here is what I get As you can see the object is the same but the collider is much worse. How can I make the same callider in spite of the orientation of the cylinderical mesh? BTW if I remove collider and do auto convex collider I get this Which is very good but the problem is that I want it to be generate from the beginning and not later when I edit the mesh collider. How can I achieve that?


How do I efficiently perform collision detection on an NxN rectangle grid? I have a simple level that is constructed from an NxN rectangle grid. Some of the rectangles are walls, and some of them are the path. The player is allowed to move only on the path they are on and also the path rectangles on the grid. So I have two kinds of rectangles in the grid "path" "wall" The player is a sprite above the grid. I want to efficiently find if the player is colliding with the wall. I want to loop through the rectangles, to see if they intersect. What is the best method?


Typical collision detection I would like to know how is the typical collision detection of most games. For example, you control a character which can move in 2 dimensional directions (except up and down). Now lets asume he walks into a wall, most of the games depending on character angle and the BB normal face will only stop the player in one axis, but will continue moving in the other along the wall axis. How is that done? I've only managed to stop the character from going through the wall by seting the position to the last one in the past frame if the new position colllisions the bounding box. But this just makes the player stop sharply and unrealisticly.


How do I do 3d collisions in isometric game? I've wondered how to get basic collision detection working in an isometric game. I'm using panda3d which has very comfortable support for bullet, ode and a small builtin physics framework. The problem is that these naturally don't work with flat images. I'm using dynamically generated quads as canvases in the 3d coordinate system. Every image or texture is mapped on one of these. The idea is to create tiles with images and place them in 3 dimensions to let panda3d do the rendering. In order to place a tree on the screen I would generate one of the dynamic flat quads and map a texture with an image of the tree on it. Then I would move the quad to the desired position and everything's fine. Panda3d manages the correct rendering order. Up to now the player object simply walks through the environment. I need to implement basic collision detection in order to solidify the trees. Browsing through previous questions I've found this one How do I handle Isometric collision detection? Unfortunately the question only targeted collisions to prevent the player from falling through the ground and allowing him to jump on platforms. This can be done comfortably with panda3d's builtin physics. Here's a picture to show you what I want The ground itself is composed of a 10x10 grid of tiles. I've used the same texture for all of them. The tree is not a sprite that's rendered in 2d. It's actually a flat rectangle with a partially transparent tree texture. The white rectangle is my player object. With the standard 3d physics I could prevent the player from walking through the quad but the tree would still be perfectly flat. I thought about adding a "dummy mesh" to have 3d collisions but that would surely come pricey in terms of performance and would spoil the neat implementation of my 3d canvases. Is there a canonical way to get 3d collisions in an isometric game ? How would you do this ? Please answer this second question on behalf of panda3d. I know that this is probably rather complicated. A link to a good article would be perfect. If you want to have a look at my code, you might want to read this question How do I use setFilmSize in panda3d to achieve the correct view? UPDATE Here's another picture that might depict the problem better


multiple contacts for SAT collision detection I have implemented SAT algorithm for obb obb intersection and I am able to generate a contact for this collision type. My problem is that SAT only generate ONE contact and in many situation I need more than one contact. For example, If I have a big cube and above it I have a small cube I need two contact (two contacts in 2D and 4 contacts in 3D) one for each bottom vertex of small cube. My question is how can I generate more than one contacts with SAT? Thanks.


How to display number of collisions on UI in Unreal Engine using nodes only? I am using Unreal Engine and I want to show on UI the number of collisions using nodes only. How can I achieve that?


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


Love2D How can I keep up with lots of small sprites' collision data? So I'm using a SpriteBatch to keep up with lots of small pieces for a falling piece puzzle game. I have an array of Quads (for different color blocks), and they are randomly added to the aforementioned SpriteBatch. Right now, the game determines when the current piece has hit the ground, then that piece is stopped and a new piece spawns that the player now can control. In order to figure out when to stop dropping the piece, I need to do a collision check. This shouldn't be hard, because I should only have to check the falling piece (unless the current falling piece causes a chain reaction). But, what type of data structure should I use? I can't use the position data of the individual Quads, because the boundary boxes will actually be a different size shape than the pieces (think triangle pieces, but I will need to use a slightly skinnier rectangle to fit upside down pieces in between right side up pieces). Should I just duplicate the (x, y) pairs using offsets with a width and height, and store them in an array, or am I missing a more obvious efficient way? I'm guessing that the play screen could fill up with several hundred of these pieces, and if I add two player mode, double that. EDIT Here's what the Quad size issue is all about


Collision Detection fails with AI cars I am making a car parking game in flash and AS3 wherein I drive my car along with other AI traffic cars moving along a specified path using Guidelines. I am using CDK for collision detection. The collision detection works fine with few AI cars, but doesn't seems to be working as required for few AI cars. When an AI car is moving on a path in a straight line it works fine.... but when the AI Car turns at 90 degress..... my car goes into the AI car (Overlapping) and it hits at the center of that AI car and then collision is Detected.... ..... I made a New path and used a new Sprite for AI car... but still the problem pursues.... I have attached the png of collision. https dl.dropbox.com u 53998590 Collision.png The AI traffic comes from Top Left corner and moves down towards bottom right corner. The problem persist with this kind of movement. when I change the movement of same AI cars from bottom right corner and moves up to top left corner then the problem does not exist. I had used CDK for collision detection. my code is as follows. addCollisonItem(mcAICars) public function addCollisionItem(mc MovieClip) collisionlist.addItem(mc) var collArray Array collArray collisionFunction() if (collArray.length gt 0 amp amp isCarCollided false amp amp game.stopCar false) trace( quot Car Collided quot ) isCarCollided true game.stopCar true if (speed gt 2) speed 1.5 speed speed if (accelerate amp amp isCarCollided) reverse false speed 1.5 return else if (reverse amp amp isCarCollided) accelerate false speed 2 return reduceLife() setTimeout(startCar, 500) Regards, Amit


How can I detect enclosed areas in an arbitrary set of overlapping lines I have game where there can be arbitrary lines, these lines can overlap. I want to find out first if there are any enclosed shapes created by overlapping lines, and then I want to fill the enclosed shape. The best guess I have at doing this comes from this other post determine if a set of tiles on a grid forms and enclosed shape. From what I can gather this would be, given a graph you can detect loops. However I can't quite figure out how to construct the graph from my data. Is this a good way to go about solving this problem? And if so, any pointers on how I might get there given a list of collisions?


How to iterate a sprite group correctly in Pygame avoiding "maximum recursion depth exceeded"? I'm making a game and I have almost finished it, but I'm usually finding the error RuntimeError maximum recursion depth exceeded when I iterate a sprite group. This is an example and the group is self.nextStageCollision() def nextStageCollision(self) for tile in self.nextStageCollision() if tile.rect.colliderect(self.rect) self.rect.x 18 20 self.rect.y 20 20 return True return False The group self.nextStageCollision() has 4 sprites (tiles) and I'm checking collision between my player and those 4 tiles to go to the next stage but I have to be doing something wrong iterating the sprite group because (I don't know why) it becomes recursive and raises the maximum recursion depth runtime error. I've debugged it and when it reaches the for each line, it loops a lot of times there (althought there are only 4 sprites in that group). I know I can increase the recursion depth, but probably it's better to not play with that and try to improve the code. So, what am I doing wrong? Is there another better way to interate a sprite group to check collisions?


Different collision effects on different objects I'm a beginner to Corona and game development. I am using a variety of objects in my game. On collision, they all perform the same function. I want them to do different things, and also want some objects to only collide with certain other objects. How would I go about doing this?


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?


How do I detect collision with isometric walls? I will use game called "Project Zomboid" as an example. Here is a pic how does it look How should I handle player's collision with walls constructed like that? It's easy to handle walkable and not walkable tiles for player, but this is different and I have no ideas how to solve this problem. Any tips?


Collision filtering by object, team I am looking for a good method to determine which objects will be considered for collision with other objects. My current idea is that each object has the following properties alwaysCollidesWith list of objects that will always trigger a collision check neverCollidesWith lost of objects that will never be considered teamCollidesWith list of objects that will be checked, provided they belong to a different team For example projectiles never have to be checked for collisions with other projectiles players are always checked for collisions with players, regardless of team projectiles are only considered for collisions if they collide with another teams players Does anyone see any weaknesses with this approach? Can anyone recommend a better approach?


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


Building dynamic bounding box hierachies I've been reading about collision detection and I saw that the first part was a coarse detection which generates possible contacts using bounding box hierarchies. I understand the concept of splitting up your objects in groups, to speed up the detection phase, but I'm a little confused on how do you actually build the hierachy, more so on what criteria is used to group them together. Do I iterate through all the objects in the scene, and check the distance between them to see where they should be inserted in the tree? Do you know some resources that may shed some light on this topic for me?


Box 2D Collision Question I am very new to Box 2D Physics world. I wanted to know how to collide 2 bodies when one is Dynamic and other is Kinematic. The whole Scenario is explained below I have 3 balls in total. I want to balls to remain in their places and the third ball to be able to move. When the third ball hits the other two balls then they should move according to the speed and direction from which they were hit. My gravity of the world is 0 because I only want z axis gravity. I would also like some one to point me towards some good tutorials regarding Box 2D basics which is language independent. I hope I have explained my scenario well. Thanks for the help in advance.


Collision Detection Code Structure with Sloped Tiles Im making a 2D tile based game with slopes, and I need help on the collision detection. This question is not about determining the vertical position of the player given the horizontal position when on a slope, but rather the structure of the code. Here is my pseudocode for the collision detection void Player handleTileCollisions() int left find tile that's left of player int right find tile that's right of player int top find tile that's above player int bottom find tile that's below player for(int x left x lt right x ) for(int y top y lt bottom y ) switch(getTileType(x, y)) case 1 solid tile resolve collisions break case 2 sloped tile resolve collisions break default air tile or whatever else break When the player is on a sloped tile, he is actually inside the tile itself horizontally, that way the player doesn't look like he is floating. This creates a problem because when there is a sloped tile next to a solid square tile, the player can't move passed it because this algorithm resolves any collisions with the solid tile. Here is a gif showing this problem So what is a good way to structure my code so that when the player is inside a sloped tile, solid tiles get ignored?


How to create polygonal or elliptical colliders by python tkinter? I am developing a primitive game by python tkinter (I use canvas). It's not a big project. It's only my own self challenge to create a game using only tkinter and standard python libraries. My problem is colliders. I need to detect collisions of game objects. First I used a circle collider (it's easy). But using only circles in a game is not good, so I decided to use polygonal or elliptical colliders, but I don't know how to do it without external libraries such as pygame. Could anyone help me? My question shorter How to detect polygons' or ellipses' collisions in python tkinter canvas using only standard libraries? P.S. And how to detect collisions of an inclined rectangle?


Determining Rectangle Circle Collision Point I'm developing a 2D game engine currently. I stuck on determining position of a rectangle that collides with a circle when its speed is added to its position. Rectangles have only x axis speed. On picture rectangles are same. Left sided rectangles x,y,width and height values are known. Second rectangle should be next position. Circles radius, x and y values are known also. (x and y values are top left position of an object). I need to find second position of rectangle. Edit I can detect collision perfectly. But I need its new position.


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


Dodge different type of obstacles I'm writing a 2D game where the player has to kill a Ninja. This Ninja is coming closer with a constant speed chasing the player. The Map has some static obstacles like stones no one can pass. The player can move too and has different types of weapons to damage the Ninja in different ways Laser instantly on whole range Gun projectile (circular) following a fixed path Trap circular floor ability which detonates after time I want the Ninja to dodge those Weapons the best he can, he is allowed to take some damage, the least is preferred. I now have different ideas how to achieve that A with 3rd dimension (time) This is working but the paths are ugly and post processing is not my favorite. Also the Graph's size is about 1000x1000, making it inefficient (on creating neighbors), i try to reduce node count by scaling the nodes to unit.hitbox (40px), which drastically improves the calcs, but the paths look even more ugly.. Theta won't work even tho I love it, but line of sight on moving obstacles is... Visibility Graph same as Theta , moving obstacles... Steering haven't tried this one yet how it performs with constant speed and moving (, delayed) obstacles Local Avoidance won't work as the weapon speed is bigger than Ninja movement speed Geometry tangents, vector projection etc.... could work well if there aren't much obstacles to dodge Do you have any other ideas how to achieve some good doing for the poor Ninja? (NINJAS USUALLY DODGE EVERYTHING... That's why I also plan to give the Ninja a Ninja Roll feature he can use every 10s to dash on some position if he can't dodge something) Representation of the raw map (little dots are 40px) A Pathfinding with time dimension and a 5px Grid Edit I'll check out D Lite and RRT Smart Edit 2 Both are not what im looking for, i will try to optimize A


How to resolve concurrent ramp collisions in 2d platformer? A bit about the physics engine Bodies are all rectangles. Bodies are sorted at the beginning of every update loop based on the body in motion's horizontal and vertical velocity (to avoid sticky walls floors). Solid bodies are resolved by testing the body in motion's new X with the old Y and adjusting if necessary before testing the new X with the new Y, again adjusting if necessary. Works great. Ramps (rectangles with a flag set indicating bottom left, bottom right, etc) are resolved by calculating the ratio of penetration along the x axis and setting a new Y accordingly (with some checks to make sure the body in motion isn't attacking from the tall or flat side, in which case the ramp is treated as a normal rectangle). This also works great. Side by side ramps, eg. and , work fine but things get jittery and unpredictable when a top down ramp is directly above a bottom up ramp, eg. lt or gt or when a bottom up ramp runs right up to the ceiling top down ramp runs right down to the floor. I've been able to lock it down somewhat by detecting whether the body in motion hadFloor when also colliding with a top down ramp or hadCeiling when also colliding with a bottom up ramp then resolving by calculating the ratio of penetration along the y axis and setting the new X accordingly (the opposite of the normal behavior). But as soon as the body in motion jumps the hasFloor flag becomes false, the first ramp resolution pushes the body into collision with the second ramp and collision resolution becomes jittery again for a few frames. I'm sure I'm making this more complicated than it needs to be. Can anyone recommend a good resource that outlines the best way to address this problem? (Please don't recommend I use something like Box2d or Chipmunk. Also, "redesign your levels" isn't an answer the body in motion may at times be riding another body in motion, eg. a platform, that pushes it into a ramp so I'd like to be able to resolve this properly.) Thanks!


Garry's Mod gamemode scripting (lua) How do I tell if an object is inside a hollow cylinder? I'm fiddling about with gMod trying to make a gamemode where you have to throw a piece of cake into a cylinder that spawns on the map. This is the code I'm using to spawn the cylinder local ent ents.Create( "prop physics" ) ent SetModel("models props phx construct windows window curve360x1.mdl") ent SetPos( Vector(math.random(100,2500), math.random(1500, 1000), 150) ) ent SetPos( math.random( 1500, 2500), math.random( 1500, 2500), 100 ) ent Spawn() cleanup.Add( self.Owner, "props", ent ) undo.Create( "Spawned Cylinder" ) undo.AddEntity( ent ) undo.SetPlayer ( self.Owner ) undo.Finish() The cake throwing part is basically just a SWEP that shoots the 'cakehat' prop. How would I test whether there is a piece of a cake inside the cylinder?


Point vs Convex Hull I'm trying to implement a simple collision response to a point intersecting a convex hull. So far I can detect if the point is inside the hull. But now I want a collision response that translates and rotates the hull away from the point so it no longer intersects. I'd like the simplest algorithm possible, I don't want to implement a physics engine or rigid bodies. Can someone point me in the right direction?


Field of vision Objective c Here's where I'm at. Here's where I want to be Here's how it's drawn SKShapeNode fov SKShapeNode node UIBezierPath fovPath UIBezierPath alloc init fovPath moveToPoint CGPointMake(0, 0) fovPath addLineToPoint CGPointMake(fovOpposite 1, fovDistance) fovPath addLineToPoint CGPointMake(fovOpposite, fovDistance) fovPath addLineToPoint CGPointMake(0, 0) fov.path fovPath.CGPath fov.lineWidth 1.0 fov.strokeColor UIColor clearColor fov.antialiased NO fov.fillColor UIColor greenColor fov.alpha 0.2 fov.name "playerFOV" playerImage addChild fov Now, I'm not expect the answer of "use this code" I'm hoping someone can point me down a logical path of determining how to emit the field of vision, and if it encounters an obstacle, it stops drawing.


Double buffer Managing Collision I'm thinking about how I should manage collisions in my game. I'm thinking about having a "Collision" class that checks for collision, and in case takes actions to resolve them. My problem is this A and B moving to the other, when they collide they must bounce. If I resolve the collisions sequentially, like calling A.collideWith(B) B.collidesWith(A) B will be stuck, because A has already updated his velocity and position, and when will be called B.collideWith(A) there won't be any collision anymore. So, is it a good idea to use a double buffer pattern? I'll write the values obtained by the collision resolver in some variables, they will be swapped to the real ones when all the collision has been resolved. In that way all should work fine. But it is a good software design? EDIT I see, yes of course i check only for half. So there should be a class that checks for collisions, and should be like checkedpairs.clear() for( Object a objects ) for( Object b objects ) if( ! a.collideWith( b ) checkedpairs.contains( a, b ) ) return Object a1 copyf( a ) Object b1 copyOf( b ) a.collideWith( b1 ) b.collideWith( a1 ) checkedpairs.add( a, b ) Instead of putting the logic for the swap in the objects themselves... But that way, I'm creating two objects for each collision, isn't too much overhead? The problem is that I don't need only the position, but al lot of physics stuff like velocity, acceleration, mass... Should I pass them? Isn't it too hard coded?


Calculating contact points with SAT After detecting a collision between two convex shapes by using separating axis theorem and calculating MTV. How can I calculate the contact points?(for applying torque to the rigid body).


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


How do I detect and handle collisions using a tile property with Slick2D? I am trying to set up collision detection in Slick2D based on a tilemap. I currently have two layers on the maps I'm using, a background layer, and a collision layer. The collision layer has a tile with a 'blocked' property, painted over the areas the player can't walk on. I have looked through the Slick documentation, but do not understand how to read a tile property and use it as a flag for collision detection. My method of 'moving' the player is somewhat different, and might affect how collisions are handled. Instead of updating the player's location on the window, the player always stays in the same spot, updating the x and y the map is rendered at. I am working on collisions with objects by restricting the player's movement when its hitbox intersects an object's hitbox. The code for the player hitting the right side of an object, for example, would look like this if(Player.bounds.intersects(object.bounds) amp amp (Player.x lt (object.x object.width 0.5)) amp amp Player.isMovingLeft) isInCollision true level.moveMapRight() else if(Player.bounds.intersects(object.bounds) amp amp (Player.x lt (object.x object.width 0.5)) amp amp Player.isMovingRight) isInCollision true level.moveMapRight() else if(Player.bounds.intersects(object.bounds) amp amp (Player.x lt (object.x object.width 0.5)) amp amp Player.isMovingUp) isInCollision true level.moveMapRight() else if(Player.bounds.intersects(object.bounds) amp amp (Player.x lt (object.x object.width 0.5)) amp amp Player.isMovingDown) isInCollision true level.moveMapRight() and in the level's update code if(!Player.isInCollision) Player.manageMovementInput(map, i) However, this method still has some errors. For example, when hitting the object from the right, the player will move up and to the left, clipping through the object and becoming stuck inside its hitbox. If there is a more effective way of handling this, any advice would be greatly appreciated.


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


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?


How to create a realistic 2D Role Playing game collision detection? I ve always wanted to create an old fashionned 2D Role Playing Game like Star Ocean, Final Fantasy, Sword of Mana and even the Tales of series, and I guess a lot of people do. But before even writing a single line of code I did a lot of research, drawing and tryouts. I've found almost all the answers to my questions but there is a problem I haven t been able to solve How do you create a realistic but yet simple collision detection, like in the games I named before? I already know several ways of calculating collision detection, look at the following examples None of these satisfy my needs. Tile based collisions are way too simple and suits more a Zelda than a Star Ocean. Plus, the drawing of each tile needs to fill up all space in order to look realistic. Pixel perfect has too many constraints. If your tile has some pixel here and there, the player will most likely get stuck in the midle of nowhere(ie in some games you get stuck on a 2 pixels width tree root). And binary masks uses too much memory and settings imo. I've read alot of documentation but I never found something that looked good to me. And all my tryouts didn't look close to what I used to play with. So if you have any good links or tutorials on how evolved 2D RPG work please let me know.


How can I convert a 2D bitmap (Used for terrain) to a 2D polygon mesh for collision? So I'm making an artillery type game, sort of similar to Worms with all the usual stuff like destructible terrain etc... and while I could use per pixel collision that doesn't give me collision normals or anything like that. Converting it all to a mesh would also mean I could use an existing physics library, which would be better than anything I can make by myself. I've seen people mention doing this by using Marching Squares to get contours in the bitmap, but I can't find anything which mentions how to turn these into a mesh (Unless it refers to a 3D mesh with contour lines defining different heights, which is NOT what I want). At the moment I can get a basic Marching Squares contour which looks something like this (Where the grid like lines in the background would be the Marching Squares 'cells') That needs to be interpolated to get a smoother, more accurate result but that's the general idea. I had a couple ideas for how to turn this into a mesh, but many of them wouldn't work in certain cases, and the one which I thought would work perfectly has turned out to be very slow and I've not even finished it yet! Ideally I'd like whatever I end up using to be fast enough to do every frame for cases such as rapidly firing weapons, or digging tools. I'm thinking there must be some kind of existing algorithm technique for turning something like this into a mesh, but I can't seem to find anything. I've looked at some things like Delaunay Triangulation, but as far as I can tell that won't correctly handle concave shapes like the above example, and also wouldn't account for holes within the terrain. I'll go through the technique I came up with for comparison and I guess I'll see if anyone has a better idea. First of all interpolate the Marching Squares contour lines, creating vertices from the line ends, and getting vertices where lines cross cell edges (Important). Then, for each cell containing vertices create polygons by using 2 vertices, and a cell corner as the 3rd vertex (Probably the closest corner). Do this for each cell and I think you should have a mesh which accurately represents the original bitmap (Though there will only be polygons at the edges of the bitmap, and large filled in areas in between will be empty). The only problem with this is that it involves lopping through every pixel once for the initial Marching Squares, then looping through every cell (image height 1 x image width 1) at least twice, which ends up being really slow for any decently sized image...


line to point collision without doing three square roots Is it possible to test a point to line collision without doing three square roots? Here's how I'm currently doing it I have point P that I want to check is on the line, and point A and B for the two ends of the line. I use the Pythagorean equation to get length PA, PB, and AB. Now I check to see if PA PB AB. if PA PB is larger than AB, the point cannot be on the line. private boolean PTLCollisionCheck(float px, float py, float ax, float ay, float bx, float by) float PA (float) Math.sqrt(((px ax) (px ax)) ((py ay) (py ay))) float PB (float) Math.sqrt(((px bx) (px bx)) ((py by) (py by))) float lineLength (float) Math.sqrt(((ax bx) (ax bx)) ((ay by) (ay by))) return (PA PB) lt (lineLength 1)


Collision detection Swinging bat racket and ball I am programming a side view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint. I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here. However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket. The following code snippet from the player entity's update function shows how the racket is updated. arcmx and armcy is the location of the shoulder joint, rstart and rend are the beginning and end of the racket. if(KEY STATUS.rleft KEY STATUS.rright) if(KEY STATUS.rright) this.rangle this.rspeed else if (KEY STATUS.rleft) this.rangle this.rspeed this.armcx this.x this.width 2 this.armcy this.y 46 this.rstartx this.armcx Math.cos(this.rangle) 40 this.rstarty this.armcy Math.sin(this.rangle) 40 this.rendx this.armcx Math.cos(this.rangle) 71 this.rendy this.armcy Math.sin(this.rangle) 71 I am pretty lost on this problem and appreciate any hints on how to approach it.


Calculating normal vector on a 2d pixelated map I want to know an efficient way to get the normal of the surface of a 2d map. suppose an object hit the map, i want the object to bounce accordingly. The problem is, the "bounding box" of said object is several pixels in size and the map has many curves. I thought about getting the pixels that collides with the object (don't ask me how) and calculating it's mean, and having the normal to be the line between said pixel and the center of the object for those familiar with worms, I want to do the same when a grenade hits the map and bounces back EDIT I'm not looking for a 100 accurate formula, I want it to be efficient and believable enough


Patterns for racing AI behaviour So let's say you've got a spline based racing AI. Assume it can already handle the basics of braking and steering around the track. How would you structure and implement collision avoidance, overtaking, drafting, blocking and other behaviours so your cars remain competitive but make interesting races? Links to papers implementations would be awesome.


How can I determine "exact moment" of collision with ray casting? I'm currently brainstorming how the physics for my game engine is going to be handled. It's top down and I'm thinking of using ray casting for collision detection. I've reached two potential problems (I want collisions to be pretty precise but of course not to operation heavy). I'd like to use 2 different polygons for each object. One box to check collisions with first and then a polygon for precise checking. Is this wise to do when also checking collisions with ray casting? Or should I go for the more precise polygon right away? Say I'm going to move an object 10 units X wise and another object 10 units Y wise how do I know "when" along this movement they collided so that if they collided after moving 5 units I could handle events at that point? (One might bounce and move back the same 5 units traveled in the same execution of my update or get instantly destroyed in which case it wouldn't collide with a third object it otherwise would have collided with) This could be a bit overkill but I still wanna know how one could go about handling this.


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


What kind of physics to choose for our arcade 3D MMO? We're creating an action MMO using Three.js (WebGL) with an arcadish feel, and implementing physics for it has been a pain in the butt. Our game has a terrain where the character will walk on, and in the future 3D objects (a house, a tree, etc) that will have collisions. In terms of complexity, the physics engine should be like World of Warcraft. We don't need friction, bouncing behaviour or anything more complex like joints, etc. Just gravity. I have managed to implement terrain physics so far by casting a ray downwards, but it does not take into account possible 3D objects. Note that these 3D objects need to have convex collisions, so our artists create a 3D house and the player can walk inside but can't walk through the walls. How do I implement proper collision detection with 3D objects like in World of Warcraft? Do I need an advanced physics engine? I read about Physijs which looks cool, but I fear that it may be overkill to implement that for our game. Also, how does WoW do it? Do they have a separate raycasting system for the terrain? Or do they treat the terrain like any other convex mesh? A screenshot of our game so far


Character collision detection on 2D array tileset based map I have a very basic collision detection working, but not quite there yet. Now as I understand I'm only checking against the left top corner of the character for collision detection. And it only works if I move character to the left. If I move to the right, the collision is not being detected. How can I check for all the sides of the character for collision and not only left top? Let's say my character sprite size is 36px. var mapArray 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 3, 3, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , function isPositionWall(ptX, ptY) var gridX Math.floor(ptX 36) var gridY Math.floor(ptY 36) if(mapArray gridY gridX ! 0) return true if(isPositionWall(boatPosX, boatPosY)) boatPosX oldPosY console.log("collision")


Pygame's sprite.collide circle() missing several frames of head on collision I've spent hours trying to figure why my collision detection was so crappy, with sprites visibly ovellaping for several frames, when I noticed the culprit could be pygame's detection callback pygame.sprite.collide circle(). I've stripped down the code and created a simple demo, and results were surprising collide circle() still returns False for several frames after its sibling collide rect() correctly detects a collision and returns True. Here is the code import pygame RED (255, 0, 0) GREEN ( 0, 255, 0) BLUE ( 0, 0, 255) BLACK ( 0, 0, 0) WHITE (255, 255, 255) SCREEN SIZE (800, 600) FPS 60 BG COLOR BLUE class Ball(pygame.sprite.Sprite) def init (self, color WHITE, radius 10, position , velocity ) super(Ball, self). init () self.color color self.radius radius self.position list(position) or 0, 0 self.velocity list(velocity) or 0, 0 self.bounds (screen.get size() 0 self.radius, screen.get size() 1 self.radius) self.image pygame.Surface(2 self.radius 2 ) self.rect self.image.get rect() pygame.draw.circle(self.image, self.color, 2 (self.radius,), self.radius) def update(self, dt 1. FPS) super(Ball, self).update() for i in 0, 1 self.position i self.velocity i dt if self.position i lt self.radius self.position i self.radius self.velocity i 1 elif self.position i gt self.bounds i self.position i self.bounds i self.velocity i 1 self.rect.center self.position pygame.init() screen pygame.display.set mode(SCREEN SIZE) clock pygame.time.Clock() background pygame.Surface(screen.get size()) background.fill(BG COLOR) screen.blit(background, (0,0)) balls pygame.sprite.Group() balls.add(Ball(color RED, radius 100, position 0, 300 , velocity 100, 0 )) balls.add(Ball(color GREEN, radius 100, position 700, 300 , velocity 100, 0 )) done False while not done for event in pygame.event.get() if (event.type pygame.QUIT or event.type pygame.KEYDOWN and event.key pygame.K ESCAPE) done True balls.update() if pygame.sprite.collide rect( balls) collision pygame.sprite.collide circle( balls) print collision if collision for ball in balls ball.velocity 0 1 balls.clear(screen, background) balls.draw(screen) pygame.display.update() clock.tick(FPS) pygame.quit() And the output False False False False False False False False False False False False False False False False False True False False False False False False False False False False False False False False False False False That's 17 frames of overlap before collide circle() realizes that hey, there's a collision there! Even at 60 FPS that's huge. The balls are almost halfway through each other, and this behavior seems to be velocity independent if I change the balls' speed or the FPS, the visual result (halfway overlap) remains, but for fewer frames. So, my question is is this a pygame bug? Or did I completely misunderstood how detection works?


What are the advantages and disadvantages of overlap testing and intersection testing? I have been looking for the advantages and disadvantages of both overlap testing and intersection testing, but I was only able to find a few disadvantages overlap testing may fail for objects moving very fast, and intersection testing makes assumptions that may lead to wrong predictions, such as a constant speed and zero accelerations. What are the advantages and disadvantages of overlap testing and intersection testing?


Finding if a point is inside of a mesh (Point in polyhedron) How can I find if a point (Vector3) is inside of a mesh? Would this work for both concave and convex objects? I read somewhere that if you raycast in both directions of every axis (X, X, Y, Y, Z, Z), take the count of the hits, and if it is even it is outside, if it is odd it is inside. I tried this and it didn't work.


Swift Why does my SKShapeNode pass through an object, pausing briefly beforehand? The code below when run on a device that s flat on the table shows a red circle (the 'ball') and a line. When I gently tip the device the circle moves towards the line. When it reaches the line, it stops which is the expected and desired behaviour. BUT if I keep tipping, the circle moves through the line. I ve been trying for 2 days to work out why grrr I just want the circle to hit the line and not go through it. Any ideas? Anything to do with the line being an 'edge'? Cheers, Andy import SpriteKit import CoreMotion class GameScene SKScene, SKPhysicsContactDelegate var ball SKShapeNode! var line SKShapeNode! var motionManager CMMotionManager() var destX CGFloat! var destY CGFloat! let ballRadius CGFloat(20.0) override func didMoveToView(view SKView) backgroundColor SKColor.whiteColor() physicsWorld.gravity CGVector(dx 0, dy 0) physicsWorld.contactDelegate self ball SKShapeNode(circleOfRadius ballRadius) ball.fillColor UIColor.redColor() ball.position CGPoint(x frame.size.width 4, y frame.size.height 2) destX frame.size.width 4 destY frame.size.height 2 ball.physicsBody SKPhysicsBody(circleOfRadius ballRadius) addChild(ball) line SKShapeNode() var lineStart CGPoint(x frame.size.width 2, y 0) var lineEnd CGPoint(x frame.size.width 2, y frame.size.height) var linePoints lineStart, lineEnd var linePos CGMutablePathRef CGPathCreateMutable() CGPathAddLines(linePos, nil, linePoints, 2) line.path linePos line.strokeColor UIColor.blackColor() line.physicsBody SKPhysicsBody(edgeFromPoint lineStart, toPoint lineEnd) addChild(line) override func update(currentTime NSTimeInterval) moveBall() func moveBall() motionManager.startAccelerometerUpdatesToQueue( NSOperationQueue.currentQueue(), withHandler data, error in var currentX self.ball.position.x var currentY self.ball.position.y self.destY currentY CGFloat(data.acceleration.x 100) self.destX currentX CGFloat(data.acceleration.y 100) ) ball.position CGPoint(x destX, y destY) import UIKit import SpriteKit class GameViewController UIViewController override func viewDidLoad() super.viewDidLoad() let skView self.view as! SKView let scene GameScene(size CGSizeMake( skView.bounds.size.width, skView.bounds.size.height)) skView.showsFPS true skView.showsNodeCount true skView.ignoresSiblingOrder true scene.scaleMode .AspectFill skView.presentScene(scene) override func prefersStatusBarHidden() gt Bool return true EDIT many thanks to Attackfarm ) I changed the moveBall() function as follows func moveBall() motionManager.startAccelerometerUpdatesToQueue( NSOperationQueue.currentQueue(), withHandler data, error in self.ball.physicsBody!.applyForce(CGVector(dx data.acceleration.x 100, dy data.acceleration.y 100)) ) which in this proof of concept demonstrates what I needed. Thanks again!


How can I test if my rotated rectangle intersects a corner? I have a square, tile based collision map. To check if one of my (square) entities is colliding, I get the vertices of the 4 corners, and test those 4 points against my collision map. If none of those points are intersecting, I know I'm good to move to the new position. I'd like to allow entities to rotate. I can still calculate the 4 corners of the square, but once you factor in rotation, those 4 corners alone don't seem to be enough information to determine if the entity is trying to move to a valid state. For example In the picture below, black is unwalkable terrain, and red is the player's hitbox. The left scenario is allowed because the 4 corners of the red square are not in the black terrain. The right scenario would also be (incorrectly) allowed, because the player, cleverly turned at a 45 angle, has its corners in valid spaces, even if it is (quite literally) cutting the corner. How can I detect scenarios similar to the situation on the right?


2D Collisions engine I am working on a fabric simulator at low level, I have done some work and at this point there are some points where I would appreciate help. The input of the program is a DRF file. This is a format used in sewing machines to indicate the needles where to move. The 2D representation is accurate, I parse the DRF info to a polyline, apply tensions and I extrude this in a openGL render. Now I am trying to achieve the 3D ZAxis physics. I tried two methods 1) Asuming information First method is based on constrains about the process of manufacturing we only take care of the knots where a set of yarns interact and comupte z separation in this crucial points. The result is regular good in a lot of cases but with a lot of botched jobs in order to avoid causistincs where this is not a good assumtion (for example, doing beziers, collisions in zones between this crucial points). We desist on this alternative when we saw there was a lot os causistic we would have to hardcode,probably creating aditional gliche. 2) Custom 2D Engine The second attempt is to aprox the yarns with box colliders 2D, check collisions with a grid, and compute new Z in funcion of this. This is by far more expensive, but leads to a better results. Although, there is some problems The accuracy of box colliders over the yarn is not absolute ( there are ways to solve this but it would be great to read some alternatives) There is not iterative process First we compute collisions pairwise, and add to each collider a list of colliding colliders. Then, we arrange this list and separate the Z axis in function of yarn's radius with center 0.The last step is to smooth the results from discrete z to a beziers or smoothing filters. This leads to another glitches. If I extend this recomputation to all the collisions of the current collisions, I get weird results because z changes are bad propagated( maybe I am not doing good this point) Some colliders are recomputed wrong ( first computed yarns have more posibilites to be altered for the last ones, leading on gliches) some of the glicthes (mainly in the first yarns computed Details of bad aproximated curves At this point I have some questions Can I fix this glitches (or a great part at least)? Glitches about bad aproximation and glitches for z recomputation A 3D engine like ODE could do the job in a reasonable time? If you need some specific code don't hestiate on ask for it. Thanks a lot!


How to implement path finding with a large number of blocking agents following similar paths? I want to implement a demo like creeps laning in Dota 2. So for simplicity, there is Left team and Right team, they are enemies. Units from Left team move toward Right base, and units from Right team move toward Left base. In their path, if those units encounter unit from enemy team, they will start to fight the enemy unit. One unit could attack an enemy unit. In their path, those units should avoid ally unit, they should not collide each other. For 2 and 4, I want to have the feature that is When encounters any enemy, one unit should seek its path to be able to fight the enemy unit. Consider this image There are some units blocked by their ally, so when an unit blocking the path disappear, another closest ally unit should move on, or move to attack their nearest enemy unit. I wonder if A should be applied for the demo. My demo is more simple than Dota 2, it does not have static obstacles, it just has dynamic obstacles (moving units). My main question is, What strategies algorithms should I apply to implement my demo? Thanks


melonJS Entity and solid block on collision layer Actually I have my player entity with 64x64 sprite animation and 18x60 hitbox also the map is made by 16x16 tiles. When my player goes some way he can pass through blocks (but not all of them). For example there are 4 situations Good (player can't pass the tile with isSolid property on collision layer) Good (player can't pass the tile with isSolid property on collision layer) Bad (player pass the tile with isSolid property on collision layer) Bad (player pass the tile with isSolid property on collision layer) Looks like melonJS checks only corners of hitbox instead of whole rectangle. Can anyone help me in this situation. UPD my PlayerEntity. var PlayerEntity me.ObjectEntity.extend( init function(x, y, settings) settings.image "player" settings.spritewidth 64 settings.spriteheight 64 this.parent(x, y, settings) this.setVelocity(3, 10) this.updateColRect(23, 18, 4, 60) me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH) this.direction 'stand2' this.addAnimation("run", 0,1,2,3,4,5,6,7,8,9 ) this.addAnimation("stand", 33 ) this.addAnimation("stand2", 44 ) this.addAnimation("jump", 29,29,29,29,29,29,29,29,27,27 ) this.addAnimation("jump2", 26,27,27,27,29,29,27,27,26 ) , update function() hadSpeed this.vel.y ! 0 this.vel.x ! 0 if(hadSpeed) this.animationspeed me.sys.fps 10 if (me.input.isKeyPressed('left')) this.jumping ? this.setCurrentAnimation('jump2') this.setCurrentAnimation('run') this.flipX(false) this.vel.x this.accel.x me.timer.tick this.direction 'left' ... right jump etc goes here ... updated this.updateMovement() if (!hadSpeed) this.setCurrentAnimation('stand') if (updated) this.parent(this) return updated )


Game map for platformer megaman style game I want to make platformer game that would be sort of like megaman. I'm using SFML library for it. I have a problem with creating a map. Should I hardcode every single platform, add it colliders and so on? I've heard that 2d array of segments would be better, but I would still have to manually fil an array that's like 1000x1000 segments. Is there an easier way to approach this?


Why does collision only work sometimes when there are multiple objects in the game? when i was making a pygame in python for the first time i kinda have a problem where sometimes the player and the object would touch and the game would not close as intended i dint seem to find the solution to this problem mostly it would work but sometimes the collision would occur but the player would clip right through i have tried numerous collision techniques which i have heard but none seem to work as well the problem would still exit here is my code import math import pygame import random RED (255,0,0) BLUE (0,0,255) bg COLOR (0,0,0) WHITE (255,255,255) pygame.init() font pygame.font.SysFont('monospace', 15) wid 720 hight 600 player size 40,40 flag 0 player pos int(wid 2),hight 2 player size 1 enemy size 50 enemy pos random.randint(0,wid enemy size),0 en list enemy pos speed 10 en num 4 block evade 0 screen pygame.display.set mode((wid,hight)) pygame.display.set caption('x wing shooter alpha v1') game over False clock pygame.time.Clock() def score count(block evade,block attack 0) text font.render('score ', 1,WHITE) text2 font.render(str(block evade block attack),1,WHITE) screen.blit(text,(0,0)) screen.blit(text2,(50,0)) def game quit() pygame.display.quit() pygame.quit() def spawn en(en list) delay random.random() if len(en list) lt en num and delay lt 0.2 x pos random.randint(0,wid enemy size) y pos 0 en list.append( x pos ,y pos ) def create en(en list) for enemy pos in en list pygame.draw.rect(screen,BLUE,(enemy pos 0 ,enemy pos 1 ,enemy size,enemy size)) def detect col(player pos, enemy pos) p x player pos 0 p y player pos 1 e x enemy pos 0 e y enemy pos 1 x1 int(e x enemy size 2) x2 int(p x player size 0 2) y1 int(e y enemy size 2) y2 int(p y player size 1 2) distance int(math.sqrt((math.pow(x2 x1,2)) (math.pow(y2 y1,2)))) if(e x enemy size gt p x gt e x) if(e y enemy size gt p y gt e y) return True elif(p x player size 0 gt e x gt p x) if(p y player size 1 gt e y gt p y) return True elif(distance lt int(enemy size 2)) return True def fall en(en list) block evade 0 for idx, enemy pos in enumerate(en list) if enemy pos 1 gt 0 and enemy pos 1 lt hight enemy pos 1 speed else en list.pop(idx) block evade 1 return block evade def col check(en list, player pos) for enemy pos in en list if detect col(player pos,enemy pos) return True else return False while not game over for event in pygame.event.get() if event.type pygame.QUIT game quit() flag 1 break if event.type pygame.KEYDOWN x player pos 0 y player pos 1 if event.key pygame.K LEFT and player pos 0 gt 0 x 10 elif event.key pygame.K RIGHT and player pos 0 lt wid player size 0 x 10 elif event.key pygame.K DOWN and player pos 1 lt hight player size 1 y 10 elif event.key pygame.K UP and player pos 1 gt 0 y 10 player pos x,y if flag ! 1 screen.fill(bg COLOR) spawn en(en list) block evade fall en(en list) if col check(en list, player pos) game over True create en(en list) score count(block evade,0) pygame.draw.rect(screen,RED,(player pos 0 ,player pos 1 ,player size 0 ,player size 1 )) clock.tick(20) pygame.display.update() else game quit()


Behavior after collision using masks overlap I'm using masks to make collision detection in a game using pygame. The detection works well, but I have had problems with the behaviour after collision. In most games, the obstacles are vertical or horizontal, making easy manipulate the velocity of objects moving. So, if the object collide, there is just two options cancel x component or cancel y component. In this way, the object stop the move only in the normal direction. But, my obstacles have any shape (not any, just rectangles and triangles) and direction, making things hard. Basically, I want to cancel the velocity component in the normal direction to obstacle in the collision point. Some help? Thanks


Collision detection 3d rectangles using SAT This question builds on a previous post asked by griffinHeart nov 2012. See link below. How many and which axes to use for 3D OBB collision with SAT Refering to the explanation answer by Ken. What if the yellow cube had a rotation so the gap was hidden. This scenario does not necessarily mean that there is a collision interception. The scenario would look something like this Which of the 9 edge edge vectors would then show that there is no collision. I am trying to implement an anti coll algo between two 3d rectangles that might have a rotation around any axis (x, y, z). I am struggling with the projection part. How to project the points onto the face normals. Hope someone can give me an answer that could lead to a solution. Thanks!


Libgdx Platform collision problem I am trying to come up with a collision function where all the cases are made. If the player (Who's hit box is a circle) collides with a platform (hit box is a rectangle) from the right the platform will push the player back. If the player collides with the platform for the top the player will stand on the platform. If the platform is to the left of the player the player cant move to the left. I am not asking how to tell if they are colliding or not but which side of the platform they are collide with where each platform is it's own object. Can someone help me make this function?


How to prevent corner slipping with a shortest axis collision solver Currently I use AABB's to represent objects in my game engine, I resolve collisions between them by finding the shallowest axis, but this leads to a problem if an object is approaching another in a way that their corners would collide at a fast velocity, they will slip past each other and resolve on the wrong axis because one penetrated too deeply, for example We can see that the red square is approaching the green rectangle. They intersect and the solver sees that the smallest intersection is on the Y axis Thus they sepparate on the Y axis, and the red square flies by the green rectangle, when it should have stopped on the left edge I'm currently at a loss on how to solve this, any sugestions or fixes would be greatly appreciated!


Simple 3D collision detection for general polyhedra I have correctly set up a SAT system. I now need to determine a simple, fast, and general purpose collision detection mechanism to identify the collision points. These points will then be used to determine the constraints for Catto's algorithm. Unfortunately there seems to be a huge set of candidate algorithms, hence my confusion. My first take would be, given that SAT tells me the candidate triangle vertex or triangle triangle for the collision, to perform the following if SAT results in a T V collision, we are done collision is at V if SAT results in a T T collision, then the collision points are found by intersecting the vertices of triangle1 with triangle2 and the edges of triangle1 with triangle2 Am I missing something big?


Checking bounds of a quad I want to know how would I tell if a quad touches another quad in my game built in Slick2D. I have a class that I named "Bounds" which has 4 "Point" objects which just store an X and a Y value and a "Bounds" object stores 4 "Point"s. Simply it has 4 2D vectors, one stores the top left, another stores the top right, another stores the bottom right and the other stores the bottom left. I need to be able to check if two quads based of those 4 coordinates are inside each other. Does anyone have an idea of what I should do?


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.


How to detect a collision and collision impact? I would like to calculate "impact" of collision if its the right word for it. My scenario is I have player, who is driving his vehicle. He then hits the wall while still in vehicle. I want to know if the collision happend and calculate the impact of collision, so later I know how much hp the player should lose depending how hard the hit was. I hope I made clear what I want to achieve. What I'm currently doing is storing the previous vehicle speed and calculating the impact like this (previousSpeed currentSpeed) frameTime. It gives me some results but it's not consistent. Any other idea? It's in 3D so I have access to 3d vectors if it helps in any way.


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?


How to get rid of an image upon collision detection in SDL? I am fairly new to SDL in C, but I have written a simple game whereby a character has to reach the end of a level and avoid bad stars on the way. If he hits a star, he dies. There are also good stars he can collect and get points. I have set up my point system so now when he hits a good star, he should get a point. However, when he hits a star, he actually gets lots of points, as long as he is touching the star, which I don't want. I think that what's happening is because the stars are moving and he rubs up against the stars each pixel he moves counts as a new collision so he gets a point per collision. Ideally, he should only get one point per star. So I have two problems 1) I need to figure out how to make it so that he can only get one point when he hits a star. 2) Since he is supposed to be 'collecting' the stars, I want to make the star disappear when he collects it. So it's similar to most of these types of games, whereby, the player collects something, it disappears and they get a point. EDIT This is struct I've made typedef struct int x, y, w, h, baseX, baseY, mode float phase Goodstar I've then referenced it in another struct like so Goodstar goodStars GOOD STARS SDL Texture goodStar GOOD STARS is equal to 100. And then here's my collision detection code Check for collision with good stars for (int i 0 i lt GOOD STARS i ) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points break So right now it only checks for a collision and then adds a point. EDIT 2 This is the code you suggested and it works for (int i 0 i lt GOOD STARS i ) if (!game gt goodStars i .awarded) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points game gt goodStars i .awarded 1 break And this is my initialisation code Initialise stars for (int i 0 i lt GOOD STARS i ) game gt goodStars i .baseX 320 random() 38400 game gt goodStars i .baseY random() 480 game gt goodStars i .mode random() 2 game gt goodStars i .phase 2 3.14 (random() 360) 360.0f game gt goodStars i .awarded 0


AABB to AABB collision response I am currently trying to resolve collision between two AABBs. I already have a function that can detect if the the two boxes are colliding and returns true if the two boxes are colliding. The problem is that I do not know what to do next. All I want to do is make sure the boxes do not penetrate each other. Where do I start? I am really confused about how to start and any help would be great. I also cannot use any libraries as this is an assignment


How to integrate Tiled maps and collision detection with pygame? I have been using pygame to make a simple rpg pokemon style game. To create maps I have used the Tiled map editor and then loading them into pygame using pytmx. I have heard that you can add object layers in Tiled to your map, and then use this information for collision detection within your game engine (in this case pygame). Unfortunately, while I know how to load the tmx file into my pygame game, I have no idea how to use the object layers for collision detection. Can anyone provide a minimal example on how to do this? The documentation that I have come across for Tiled appears to be quite minimal and still an active work in progress. As a result I have not been able to find information on using Tiled and object layers for collision detection in pygame.


Bringing islands close together programmatically I generate island continent maps and I want to make a grand archipelago of sorts where all these islands are located. The problem is that I don't know a smart way to place the islands programmatically so that the keep a minimum distance from each other. Sure, I can create a quadtree but then how do I place it? Placing it on top of another island and move it away in a random direction? I'm attaching a photo of what I want to do, easily done in Paint .NET from 6 individual maps. The scale I'm talking about would be placing about 3 10 continents, each with a resolution of 4Kx4K upwards. (I'll only allow reflections and translations in placement, to preserve some 4 8 connectivity pixel work that I've done for the maps) What I'm NOT looking for a global minimum solution ( all islands as close together as possible) using a heavyweight physics maths library or tons of code a super simplistic solution either (e.g. calculate OBBs and use those to resolve collisions)


Targeting logic for 100.000 units army I am making an army fight for my website armyfight. There can be fights of hundreds of thousands units. I am looking for better unit targeting. in jsfiddle is an example. var enemy 2 3 object inside with unit data , 5 6 var ally 4 3 function unit searches for target(y, x) var closest y iterate Y(y) var unit target iterate X(closest y, x) return unit target Searches for closest target at Y axis function iterate Y(y) if ( .has(target, y)) return y else var y parseInt(y) for (var i 1 i lt 300 i ) If y 4, it checks 4 1 5 (positive side) if ( .has(target, String(y i))) return (y i) Else if y 4, it checks 4 1 3 (negative side) else if ( .has(target, String(y i))) return (y i) if didn't find anything, just returns same y as given return y Searches for closest target at X axis function iterate X(y, x) if ( .has(target y , x)) return y y, x x else var x parseInt(x) for (var i 1 i lt 300 i ) If x 4, it checks 4 1 5 (positive side) if ( .has(target y , String(x i))) return y y, x x i Else if x 4, it checks 4 1 3 (negative side) else if ( .has(target y , String(x i))) return y y, x x i if didn't find anything, just returns same x as given return y y, x x Here first i iterate on Y axis, later on X axis. But on different army positions it gives wrong results. In this example, units are looking for targets by simply iterating. It is not very good for a huge army fight of hundred thousands units. Best would be to iterate like here, when iteration process is much faster leading to first hit success function iterate X(y, x) return .find(enemy y , function (value, key) return parseInt(key) gt x ) But this iteration works only 0..100, or 99..100, but not 100..0, so i can't iterate objects in reverse mode. So if ally is 5 10 , 99 and enemy is at 5 100 , enemy unit would find closest ally as 5, 10 instead of 5, 99 . If it would be an array iterating backwards from 100 to 0, so it would be first hit success. But can asotiative array be reverse iterated? Any suggestions please on structure? Maybe change units structure from objects to arrays or mix? But then I have problems with associative arrays. I am looking for an explanation or example about the structure and for a faster iteration for units targeting. And i am also looking for websites, where i could ask these heavy logic questions? I have more of them.