_id
int64
0
49
text
stringlengths
71
4.19k
18
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.
18
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.
18
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.
18
Libgdx If Rectangle overlaps anything? I've written a code that allows me to talk with an NPC. This works as long as there is only 1 NPC on the map. I'll explain why. public void getNPCCollision() for (int i players.size() 1 i gt 0 i ) Player player players.get(i) for (int j beings.size() 1 j gt 0 j ) Being being beings.get(j) if(player.getBounds().overlaps(being.getBounds())) setX(oldX) velocity.x 0 setY(oldY) velocity.y 0 else if(player.getBounds().overlaps(being.getTalkingBounds())) canTalk true talkAbleBeing being else talkAbleBeing null canTalk false I check every update if my Player walks into an NPC's Talking Rectangle. It goes by every NPC on the map. The thing is If I'm not on NPC 1's rectangle but on NPC 2's rectangle, It'll still set canTalk to False because I'm indeed not in his rectangle. Is there any way I can fix this issue? Please, any help appreciated.
18
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.
18
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)?
18
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.
18
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?
18
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!
18
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.
18
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.
18
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.
18
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?
18
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?
18
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.
18
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
18
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.
18
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?
18
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.
18
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
18
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
18
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?
18
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?
18
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?
18
How many and which axes to use for 3D OBB collision with SAT I've been implementing the SAT based on Dynamic Collision Detection using Oriented Bounding Boxes PDF On page 7, in the table, it refers the 15 axis to test so we can find a collision, but with just Ax, Ay and Az, I'm already getting collisions. Why do i need to test all the other cases? Is there any situation where just Ax, Ay and Az are not enough?
18
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?
18
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?
18
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?
18
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?
18
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.
18
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?
18
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?
18
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.
18
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?
18
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
18
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!
18
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?
18
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?
18
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.
18
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?
18
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).
18
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...
18
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.
18
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 ?
18
What data should a generic collision detection system gather? I'm working on a relatively generic 2D AABB collision detection system for a game engine, and I've re written it more times than I'd like to admit, due to not calculating or recording specific details of each collision. Right now, this is what I'm collecting Collision time as a fraction of an update cycle in the game loop. Location of the collision. ID of the colliding object. Each object has a Set that holds this data for each collision (I'm working with a component entity system) so other systems can use the recorded data. The problem I just ran into was that I needed to know which side of the object the collision takes place on. What other values or points of interest should I calculate or record, per collision? What do you look for in a standard collision detection system?
18
How 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.
18
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...
18
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)
18
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.
18
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
18
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.
18
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.
18
Separating Axis Theorem and rotated objects Quick question which hopefully won't require thralling through my code. I have a working implementation of SAT for 3D collision detection but I'm having some problems with dealing with rotated objects. So what I have done, is every frame I rotate every point in both objects by their rotation quaternions. This feels excessive, especially if I am going to be translating scaling rotating every vertex in every object on every frame for the collision detection. I would hope there's a way of implementing my SAT implementation to work with rotated normals only, and not need the rotated projections to compensate, but that doesn't seem to be working. Could anyone provide me with a brief explanation with how SAT should be expected to handle rotations? Can we rotate certain points, or perhaps get some sort of post projection rotation value to skew our projections like we can with translations? Thanks
18
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
18
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")
18
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?
18
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?
18
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.
18
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!
18
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?
18
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!
18
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
18
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 )
18
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?
18
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()
18
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
18
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!
18
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?
18
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!
18
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?
18
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?
18
LibGDX Colllisions between bullets and enemies in arrays I am writing a "Gauntlet" style game. So far I have managed to successfully detect collisions between my player object and my ghost enemy objects, and when they collide they drain the player's energy. The Ghosts are stored in an ArrayList. I now have bullets which the player can fire, these are instantiated from the Player class and added to another ArrayList called bullets. I typically have around 50 ghosts on the screen dotted around the map. ArrayList lt Ghost gt ghosts new ArrayList lt Ghost gt () ArrayList lt Bullet gt bullets new ArrayList lt Bullet gt () The ghosts and bullets are added to these lists when spawned fired I have tried to implement a method as per below, to try and determine whether a ghost's bounding rect and a bullet's bounding rect overlap, as follows Check if a ghost has been hit by a bullet public void checkGhostsHit() Iterator lt Ghost gt iterEn ghosts.iterator() while ( iterEn.hasNext() ) Ghost g iterEn.next() initialise the bullet iterator each time here Iterator lt Bullet gt iterBul Player.bullets.iterator() while ( iterBul.hasNext() ) Bullet b iterBul.next() if ( b.getBoundingRect().overlaps( g.getBoundingRect() ) ) Gdx.app.log("Enemy", " Hit") iterBul.remove() iterEn.remove() This method is being called from my main render loop but I cannot get it working for love or money. I have tried various forms of the above method, including 'For' loops etc. Am I performing the check in the correct place? Should the Bullet class instance iteself be checking for a collision, or is the above approach the correct idea. As you can tell I'm a noob to this and I am still struggling with working out which activities should be undertaken by particular game Classes.
18
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.
18
How to get distance from point to line with distinction between side of line? I'm making a 2d racing game. I'm taking the nice standard approach of having a set of points defining the center of the track and detecting whether the car is off the track by detecting its distance from the nearest point. The nicest way I've found of doing this is using the formula d Am Bn C sqrt(A 2 B 2) Unfortunately, to have proper collision resolution, I need to know which side of the line the car is hitting, but I can't do that with this formula because it only returns positive numbers. So my question is is there a formula that will give me positive or negative numbers based on which side of the line the point is on? Can I just get rid of the absolute value in the formula or do I need to do something else?
18
How 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
18
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
18
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!
18
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.
18
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)
18
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.
18
Fast 2D collision detection in an unbounded space I'm trying to do collision detection on a large number of entities of greatly varying size in an unbounded space. The entities are circles, so it's relatively easy to check if two are colliding. However, with a large number of entities the simulations slows down a lot when I code it to check every entity against every other (for n entities, I believe it is n (n 1) 2 checks, way too many!) Here's my though process so far First, I considered using a grid of some sort, like described in steps 1 2 of the answer here Fast, accurate 2d collision There are, however, a few problems with this 1) It is an unbounded space. Where do I start and end the grid? How do I determine the size of each square in the grid in a world where some objects are literally tens of millions times larger the other objects? 2) Even if I somehow manage to adjust the size of the grid every frame without using too much processing power, so that it adjust to fit the most distant objects, (unlikely that I could do this efficiently) this is still not a solution. If tons of objects are clustered in a 10,000x10,000 space, and one object goes shooting off into space 100 billion units of distance away, the grid would "zoom out", leaving all of the objects in the smaller 10,000x10,000 space in one square, which would defeat the purpose of making a grid in the first place. For these reasons, I'm thinking that a simple grid is not the best idea... I looked at BSP's, and I admit that I don't fully understand the concept, but it seems like it does not apply well to my situation (especially since I am using circles and BSP seems better suited to a more complicated polygonal world). Quad trees seem promising (something like this perhaps http www.youtube.com watch?v qJJnzSLrC1E) but I foresee at least two potential issues 1) I can calculate the "farthest away objects" each frame to give calculate GreatestXValue, LeastXValue, GreatestYValue, and LeastYValue, for each frame. From that I have a rectangle to work with that contains all entities. However, I will have to redo this each frame, which means that I have recreate the the entire quadtree each frame no shortcuts on calculations done in previous frames. Is this a problem or do most game simulation programmers have to completely recreate the quadtree each frame anyway? 2) (Probably the bigger problem) How do I handle a massive object in the vincinity of many small objects? Think about many circles with radius 5 being very close to, resting against, or colliding with a circle with radius 100,000. That massive object will be in many, many grid squares, and it seems to me that the situation would force the creation of a tree that is far too broad and deep. Am I on the right track with my thought process? Where do I go from here? Thank you very much for your time and help!!
18
Godot raycast colliding too high I am making an fps that uses a raycast for shooting. I used some suggestions taken from a few reddit pages, but it's mostly my own code. It was working properly, until I noticed that when you shot up above the enemy, it still registered as a hit. Does anyone know why this might be happening? code func use weapon() Raycast.force raycast update() if Raycast.is colliding() var collider Raycast.get collider() if collider if collider.has method( quot takedamage quot ) collider.takedamage(10)
18
Slopes vs. Rectangles Different Collision Points My platformer has both rectangular tiles and right triangle slopes with rectangular hitboxes. My sprites are also rectangular. Collision with only rectangular tiles works well. Even if there are multiple rectangular tiles, collision still works pretty well. Sprites can collide with individual slopes correctly as well, however, they collide at a different point. In order for the character's feet to be walking down the slope instead of hovering over it, the collision point for slopes is the bottom center point. For rectangles, it is either corner. The problem is moving from a rectangular tile onto a sloped one. The sprite resolves by the corners first, since it is resting atop a rectangular tile. However, the center point is resting above the slope, and the sprite will not move onto the slope until it is entirely moved off of the rectangular tile. Here's a diagram How can I reliably use two different collision points for different tiles in a way that allows sprites to walk between rectangular and sloped tiles?
18
Collision detection formula for getting intersection point I need help with collision detection algorithm from this paper http www.peroxide.dk papers collision collision.pdf I assume I am colliding with sphere of radius 1, just to make everything not important easier...I am concerned with formula, which finds intersection point with plane (page 14) planeIntersectionPoint basePoint planeNormal t0 velocity where basePoint center of Sphere planeNormal normalized normal vector to colliding plane t0 number from 0,1 interval, first moment from this interval during which collision happens, assuming we are moving with velocity vector velocity velocity vector I think that this formula doesn't work... Assuming that I am already intersecting with plane at t0 0, I just get planeIntersectionPoint basePoint planeNormal What gives me point which doesn't even belong to plane, what fails further parts of the algorithm, when I check if intersection point is in triangle... I will be grateful for every answer... Is the algorithm wrong, or that's me misunderstanding something?...
18
How is raycasting implemented I know what it's used for, I know what it does. What I am essentially asking is what is the math code behind how it works? I'm aware that any custom implementation would likely be slower than an engines official implementation, I just am interested in how it works.
18
Roguelike 2D Collision Detection I'm just a normal guy trying to do some basic collision detection but I suck at it. I either get stuck in a wall or I go in reverse in the wrong direction trying to update the player position to a non collision part. So here is how I check for collision and this function will return true or false. True if collision and false if not. roguelike.player.collision function() var player roguelike.player for(var i 0 i lt roguelike.map.rooms.length i ) var room roguelike.map.rooms i if(player.x gt room.x amp amp player.x lt room.x room.width amp amp player.y gt room.y amp amp player.y lt room.y room.height) return false return true This function works just fine just like expected. But it's when I try to stop the player when he hits a wall is where I get bugs. When the player goes down and hits a wall he gets stuck there. Here is the function that updates the player position. roguelike.update function() var player roguelike.player Left if(player.moving.left amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Up if(player.moving.up amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Right if(player.moving.right amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() down if(player.moving.down amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() player.savePosition() So what I do is check what direction the player is moving and if there is no collision detected then the player is free to move. Otherwise if there is a collision I put the player position as the last position he was when there was no collision so he will be free to move. This works going left, up, and right, but not going down. Going down the player gets stuck in the collision and the resetPosition function doesn't put the player back in the safe zone. So I know there must be a better way. And I would appreciate your advice on what you think that way should be.
18
How do Axis Aligned Bounding Boxes update with rotations? I have a bounding box class with a min (x,y,z) and max point (x,y,z). The object that is being rotated has a rotation matrix (3x3 matrix), but I don't know how to update the bounding box with rotations. I'm also a little confused if I should be using Oriented Bounding Boxes instead. For example, if the 3D object is a cube then the bounding box would rotate with it so they share the same 8 vertices at whatever rotation the cube is in. What's the best way to represent the bounding box for rotations and test for collisions?
18
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 ?
18
2D Distance Field as collision handler method Pixeljunk Shooter has really cool fluid simulation. I found the dev's video explaining what they did. Here I understand that it is particle based simulation Smoothed Particle Hydrodynamic I can find adequate resources and even books covering this topic, but I can't find resources for the "collision" All I can find about using distance field for collision are very tough article and some vague description The second resource states Using a signed distance field then makes it very easy to check if a particle is colliding with our environment simply sample the distance field at the particle position and if the magnitude of the distance is negative we have a collision (ignoring the potential for tunneling for the time being). Once a collision is detected we can then backtrack along the particle trajectory until we find where the particle collided with the surface. To calculate the collision response we then need to determine the surface normal this is again easy as we simply need to calculate the gradient of the distance field and normalize the result. Does it mean that I just backtrack my particle till it is no longer "inside the object"? Then take average distance from surrounding, then take normalized average as "normal vector of the sourface"? Is that "all" I need to do? If such is the case, don't I need to render only "inside" of distance field? I don't need how close edges are when I am outside an object? Or do I need to know that as well? I really need clear step by step teaching material in which I can really look at it and read it through to understand. Are there any resource that teaches this technique?
18
Collision detection enhancement I am developping a spaceinvader like game. There comes the problem of how to handle collision detection. At first I was doing like that forEach(fireBall fireBalls) forEach(stormTrooper stormTroopers) if (collides(fireBall, stormTrooper)) Explode But then when playing I had the feeling the game was slowing down at some point, and I tought it had something to do with the multiple elements and the double loop. So I tried to break the loops whenever I had the chance, changing the forEach loops to for loops at the same time for (var i 0 i lt fireBalls.length i ) if (stormTroopers.length gt 0 amp amp fireBalls i .y gt stormTroopers 0 .y) break for (var j 0 j lt stormTroopers.length j ) if (fireBalls i .y gt (stormTroopers j .y 31)) break If the fireball isn't on the same "y" as any stormtrooper, the fireballs following are not going to be either, so no need to check. Same for the stormtroopers loop. This works only if the list is ordered, meaning the first stormTrooper of the list has the highest "y" value. The problem in my game is that all stormTroopers don't have the same speed, so I need to sort the list each time. This leads to my question in order to enhance the performance, I tried to break the loops, but for that I had to add a new operation sort the list of the stormTrooper. Is it worth it?
18
Continuous Collision Detection So I'm playing around with the separating axis theorem and collision. Obviously the problem of what face it collided with arose. I need the unit normal which is tangent to that face it collided with to resolve depth penetration. For rectangles it's easy. Update Y velocity If collision collision happened on the y axis. Update X velocity If collision collision happened on the x axis. But I wanted a more general that would work with all cases. I came up with two solutions 1.) So I thought about the solution above with a triangle. Obviously it wouldn't work because the rectangles faces are axis aligned and a triangles faces are not. So I figured I could just project the face and velocity using the dot product to solve it like the rectangle but for every face with its own axis. This would of course involve checking collision with the whole shape again for each face. 2.) I also figured I could do Polygon v Ray collision detection to figure out what face it collided with. My question is Which solution is faster? Or is there a better one that hasn't come to my mind? I don't know how to do Polygon v Ray collision but I would guess that foreach face, find intersection point between ray and segment of face.
18
Collision detection for sloping tiles I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out. First, some background. My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen). So, my 'slope tile' looks something like this Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think. Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile. I then multiply that by my slope (slope being height width or 100 102 in my case) I then divide by 2 to get the centre Finally, I subtract that result from the height of the tile (to invert it) This gives me the vertical center which I can compare with the centre of my sprite to check for collision. So, my code looks like this VertTileCentre Math.round(tileYCoord tile.quadHeight ((slope (spriteX tileX)) 2)) Results When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly. Edit 1 results from further experimenting I've noticed that the sprite when at the top left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up because it was hitting solid blocks behind (which have their own collision detection) Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) therefore if I remove the solid blocks, it works OK. So I have no idea why not dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!
18
How to handle collisions without ugly conditionals and type checking? (I asked a similar question, but this one is far more specific). How can I handle collisions without having to do a lot of type checking and if statements? People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision. I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if statements inside the handleCollision methods. For example (in psuedocode) class CollisionDetector foreach entity in entities foreach otherEntity in entities if(collision(entity,otherEntity)) entity.handleCollision(otherEntity) class Entity .. stuff omitted void abstract handleCollision() class Alien extends Entity .. stuff omitted void handleCollision(Entity entity) lots of ugly conditionals and type checking if(entity instanceof Missile) die() if(entity instanceof Alien) lifePoints ((Alien)entity).getDamagePoints() if(entity instanceof Wall) setVelocity(0,0) .. etc In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case. Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?
18
How should I learn about collision detection? If I want to use physics engine for my game then how should I go to learn collision detection algorithms? When I read AI book for games, the book talks about collision detection, so I want to learn it, but what kind of book would be best? If I had to choose to go and learn it what would you advise me to read? A physics book. (Game physics H.Ebrely) A real time collision detection book. (Same author) I don't know much about algorithms, some people say it's better to start with a physics book, because real time collision detection book depend heavily on algorithms.
18
Can't find out why aren't those collisions framerate independent I'm making a 2D Platform game and I'm having trouble with my collision detection. It doesn't seems to be framerate independent even though I used deltatime there. The problem is that at 60fps, a collision is sometimes detected too early whereas at 500fps there's no problem (so it really seems like this isn't framerate independent but I don't know why). Here's a video of the game running at 60fps https www.youtube.com watch?v P0hRJbw gcw And here's the code which is moving my character (I inspired myself about 2D Collision detection from the youtuber dermetfan) Makes the entity jump void Entity jump() m onGround false setVelocity(sf Vector2f(getVelocity().x, 500)) What to do at each frame void Entity update(sf Time dt) if (getVelocity().y gt 800) setVelocity(sf Vector2f(getVelocity().x, 800)) else setVelocity(sf Vector2f(getVelocity().x, getVelocity().y m map gt getGravity() dt.asSeconds())) checkCollisions(dt) Collision functions void Entity checkCollisions(sf Time dt) float oldX getPosition().x float oldY getPosition().y bool collX false bool collY false setPosition(getPosition().x getVelocity().x dt.asSeconds(), getPosition().y) Setting the position on x m collisionIncrement (getSize().x lt getMap().TILE SIZE) ? getSize().x 2 getMap().TILE SIZE 2 if (getVelocity().x lt 0) collX collidesLeft() Using collision tests else if (getVelocity().x gt 0) collX collidesRight() if (collX) Testing if there was a collision setPosition(oldX, getPosition().y) Correct position setVelocity(0, getVelocity().y dt.asSeconds()) setPosition(getPosition().x, getPosition().y getVelocity().y dt.asSeconds()) Setting the position on y m collisionIncrement (getSize().y lt getMap().TILE SIZE) ? getSize().y 2 getMap().TILE SIZE 2 if (getVelocity().y gt 0) collY collidesBottom() m onGround collY else if (getVelocity().y lt 0) collY collidesTop() if (collY) Testing if there was a collision setPosition(getPosition().x, oldY) setVelocity(getVelocity().x dt.asSeconds(), 0) bool Entity collidesRight() for (float step 0 step lt getSize().y step m collisionIncrement) if (getMap().isCollideable(getPosition().x getSize().x, getPosition().y step)) return true return false bool Entity collidesLeft() for (float step 0 step lt getSize().y step m collisionIncrement) if (getMap().isCollideable(getPosition().x, getPosition().y step)) return true return false bool Entity collidesTop() for (float step 0 step lt getSize().x step m collisionIncrement) if (getMap().isCollideable(getPosition().x step, getPosition().y)) return true return false bool Entity collidesBottom() for (float step 0 step lt getSize().x step m collisionIncrement) if (getMap().isCollideable(getPosition().x step, getPosition().y getSize().y)) return true return false
18
Collision detection with multiple polygons simultaneously I've written a collision system which detects resolves collisions between a rectangular player and a convex polygon world using the Separating Axis Theorem. This scheme works fine when the player is colliding with a single polygon, but when I try to create a level made up of combinations of these shapes, the player gets "stuck" between shapes when trying to move from one polygon to the other. The reason for this seems to be that collisions are detected after the player has been pushed through the shape by its movement or gravity. When the system resolves the collision, it resolves them in an order that doesn't make sense (for example, when the player is moving from one flat rectangle to another, gravity pushes them below the ground, but the collision with the left hand side of the second block is resolved before the collision with the top of the block, meaning the player is pushed back left before being pushed back up). Other similar posts have resolved this problem by having a strict rule on which axes to resolve first. For example, always resolve the collision on the y axis, then if the object is still colliding with things, resolve on the x axis. This solution only works in the case of a completely axis oriented box world, and doesn't solve the problem if the player is stuck moving along a series of angled shapes or sliding down a wall. Does any one have any ideas of how I could alter my collision system to prevent these situations from happening?
18
Collision within a poly For an html5 engine I'm making, for speed I'm using a path poly. I'm having trouble trying to find ways to get collision with the walls of the poly. To make it simple I just have a vector for the object and an array of vectors for the poly. I'm using Cartesian vectors and they're 2d. Say poly 550,0 , 169,523 , 444,323 , 444, 323 , 169, 523 , it's just a pentagon I generated. The object that will collide is object, object.pos is its position and object.vel is it's velocity. They're both 2d vectors too. I've had some success to get it to find a collision, but it's just black box code I ripped from a c example. It's very obscure inside and all it does though is return true false and doesn't return what vertices are collided or collision point, I'd really like to be able to understand this and make my own so I can have more meaningful collision. I'll tackle that later though. Again the question is just how does one find a collision to walls of a poly given you know the poly vertices and the object's position velocity? If more info is needed please let me know. And if all anyone can do is point me to the right direction that's great.
18
Combining Many Small Colliders into Larger Ones I am creating a game using a tile map made of many thousands of grid squares. At the moment, each square has a square collider on it for checking collisions. However, with many thousands of tiny blocks, checking them all for collisions is inefficient. If I had known the tilemap was going to look like this in advance, I could have just used 3 or 4 big colliders rather than thousands of tiny ones Is there some sort of standard algorithm for combining many small adjacent tiles into maximally large ones? If so, could someone describe it here, or point to literature on such algorithms? Alternatively, maybe pre processing the tile colliders in this way is completely the wrong approach. If so, what is the correct one to deal with the efficiency of an extremely large number of colliders?
18
Player won't move correctly due to gravity force pushing him into the ground I am making a tilemap platformer with pygame ad I defined the X and Y movement for the player and also a Y force that represents the gravity force to make it jump correctly. However, when my player falls off to the ground and the game begins, it doesn't move correctly neither to the right nor to the left direction due to the gravity force that keeps pushing him to the down. In addition to that, when the player jumps and i move it to the right, it's like it doesn't recognize the collision with the bottom rect of the wall (see gif below for a visual explanation of that). I tried disabling that gravity force when the player hits the ground and enable it when the player jumps but it didn't work as expected and I've got problems managing collisions (also, it doesn't make sense to disable gravity, right?) Here's a gif of the issue i'm facing with Here's my Player class class Player(pg.sprite.Sprite) def init(self, game, x, y) self.groups game.sprites pg.sprite.Sprite.init(self, self.groups) self.game game self.image pg.Surface((TILESIZE, TILESIZE)) self.image.fill(GREEN) self.rect self.image.get rect() self.move left self.move right False self.pos pg.math.Vector2(x, y) self.acc pg.math.Vector2(0, GRAVITY) self.vel pg.math.Vector2(0, 0) def jump(self) self.vel.y 3 def update(self) self.vel.x 0 if self.move left self.vel.x PLAYER SPEED if self.move right self.vel.x PLAYER SPEED self.vel self.acc self.pos self.vel self.rect.x self.pos.x TILESIZE self.rect.y self.pos.y TILESIZE if self.vel.y gt 0.5 self.vel.y 0.5 hits pg.sprite.spritecollide(self, self.game.walls, False) if hits if self.vel.x gt 0 self.pos self.vel self.rect.right hits 0 .rect.left self.vel.x 0 if self.vel.x lt 0 self.pos self.vel self.rect.left hits 0 .rect.right self.vel.x 0 hits pg.sprite.spritecollide(self, self.game.walls, False) if hits if self.vel.y gt 0 self.pos self.vel self.rect.bottom hits 0 .rect.top self.vel.y 0 if self.vel.y lt 0 self.pos self.vel self.rect.top hits 0 .rect.bottom self.vel.y 0
18
How can I determine which tiles in a tilemap an oriented bounding box (OBB) overlaps? I need to detect collisions between an oriented bounding box and a static tile map. My tile map class looks something like this function Tilemap(width, height, tiles) this.width width Width of the map in tiles this.height height Height of the map in tiles this.tiles tiles 1D array containing tiles, grouped by row Tilemap.prototype.getTile function (x, y) return this.tiles y this.width x Tilemap.prototype.setTile function (x, y, value) this.tiles y this.width x value My question is this How can I determine which tiles an OBB, represented as an array of vertices, overlaps? (I am writing in JavaScript but answers for any language would be appreciated.)