_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
18 | Unit collision avoidance for RTS I'm developing an RTS, and having a little difficulty with collision detection. From what I understand RTS generally don't bother with collision detection and just try to avoid collision, and that is what I am trying to accomplish. My game uses a grid for static obstacles, but units are not bound to the grid for movement. How do I allow for units to avoid collisions, both with static obstacles and with other units? Right now my workaround is to redirect units around static obstacles every time they move from point to point (and every time a new obstruction is placed on map, units replan their routes). This doesn't seem like an ideal solution, but it works. I have no idea how to handle unit unit collisions. |
18 | How to make my character slide (not bounce) off a slope My character needs to slide and not bounce off a slope. The solutions I found here use a Reflection vector, but they make my character bouncy when they run downwards a slope. var reflectVector normal.clone().multiplyScalar( this.velocity.clone().dot(normal)) this.velocity.addSelf(reflectVector) How can I make my character simply stick to the terrain when they walk? |
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 | 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 | Collision for mobile game I'm writing a little game in as3 using Starling, and I need to check collision between 2 boats that can rotate. I don't need the pixel perfect collision, but bounds collision is not enough too. The boat look more or less like this I was thinking about create one square on the back of the boat and a triangle on the front, than for each boat, check if the square collide with the other boat square or triangle, and the same for the triangle. I just don't know how to do that, I don't know if it's possible with the Shape.hitTest, or if it's the best way to do that. What can I do? |
18 | Swept AABB vs Line Segment 2D I've really exhausted as much as Google has to give, I've spent a solid week googling every combination of words for an "AABBvsLine sweep", downloaded countless collision demos, dissected SAT intersection examples and an AABBvsAABB sweep trying to figure out how to approach this. I've not found a single thing covering this specific pairing. Can anyone shed any light on how to get the hit time of a swept AABB vs a Line segment in 2D? I'm still getting familiar with the SAT but I do know how to implement it to a degree, I'm just not sure how to extract the hit time from the velocity in the non axis aligned separating axes for the sweep. I really would appreciate anything at the moment, some code or even some helpful links, I'm at my wits end! |
18 | How to differentiate landing on top of an object from falling down the side? I am looking for a conceptual solution to my problem. It's a simple platformer alike game where player can move horizontally during free fall. Consider those two cases In the first case, from game experience point of view, the player should land on top of the box and in the other case he hit the left edge, hence the player should fall down. However, from my code point of view ("real behaviour"), both those collision detection cases are identical. I am not sure how to separate them. In both cases the vertical velocity is positive (falling down) and the user is moving with some fixed positive horizontal velocity. (moving right) From a collision standpoint the two cases are identical, I think. How can I tell whether I should put the player on top of it or let him fall? |
18 | Proper Angled Top Down Wall Collision? Sorry about the vague title, it's kind of hard to say what I want to do in a few words. In my top down game, I'm having a problem implementing proper collision for walls facing north (that is, you can actually see the surface of the wall, as opposed to the other directions, where you can see just the top). I have a proper bounding box that detects the alpha values of the sprite, and generates a proper bounding box around only the visible pixels, like so http a.pomf.se kfrxtm.mp4 However, when dealing with walls, I run into a problem. With my current implementation, there are two options I have Set the walls so that the player can pass through them. This leads to the player walking "on" the walls, like so Set the walls so that the player can not pass through them. This leads to the player's head colliding on the bottom of the wall, like so In the image, the player can not move forward any more. My solution to this, would be to place the bounding box around the player's feet. However, this would interfere with my alpha based system, and other collision systems (enemies hitting the player, etc.) How should I approach this? If my question is unclear, I can provide more images and descriptions of what I'm trying to achieve. |
18 | Swept AABB vs Line Segment 2D I've really exhausted as much as Google has to give, I've spent a solid week googling every combination of words for an "AABBvsLine sweep", downloaded countless collision demos, dissected SAT intersection examples and an AABBvsAABB sweep trying to figure out how to approach this. I've not found a single thing covering this specific pairing. Can anyone shed any light on how to get the hit time of a swept AABB vs a Line segment in 2D? I'm still getting familiar with the SAT but I do know how to implement it to a degree, I'm just not sure how to extract the hit time from the velocity in the non axis aligned separating axes for the sweep. I really would appreciate anything at the moment, some code or even some helpful links, I'm at my wits end! |
18 | Box2d too much for Circle Circle collision detection? I'm using cocos2d to program a game and am using box2d for collision detection. Everything in my game is a circle and for some reason I'm having a problem with some times things are not being detected as a collision when they should be. I'm thinking of rolling up my own collision detection since I don't think it would be too hard. Questions are Would this approach work for collision detection between circles? a. get radius of circle A and circle B. b. get distance of the center of circle A and circle B c. if the distance is greater than or equal to the sum of circle A radius and circle B radius then we have a hit Should box2d be used for such simple collision detection? There are no physics in this game. |
18 | Organizing movement, collision detection, and collision resolution There's many articles on the internet focusing on how to implement movement, collision detection, or collision resolution. What I'm wondering is how to put them together, specifically in what order to perform them. Should one iterate through all physics objects and do movement, collision detection and resolution for each (approach A), or perform movement for all objects, then detect all collisions, and finally resolve all collisions (approach B), or some combination thereof? Is there an approach that is universally superior? If not, what are the pros and cons for each approach (including ones I haven't listed)? Approach A for (all objects) object.move object.detect collisions object.resolve collisions Approach B for (all objects) object.move for (all objects) object.detect collisions for (all objects) object.resolve collisions |
18 | Subdived objects in different shapes Currently I'm working on an Android OpenGL 3D game and now I want to implement a collision detection. For this I want to use oriented bounding boxes but here is my problem. For a normal oriented bounding box I have to store the middle and then the length into every dimension. Now let's say I have a tree and of course my character can walk under the treetop but not into the tree trunk. I tried to sketch up the different bounding boxes here Tree as two rectangels Normal bounding box x If you think about the collision detection in the first sketch you can walk under the treetop because the border of the tree is subdivided into different shapes and the outline of a tree is still visible. In the second picture you can't tell something about the outline of the object because you only have one big box around the whole object so you can't walk under the treetop. You see the first method is much better then the second method for my plan. Now my question Do you have any ideas how I can subdivide my objects into different shapes? Maybe even in triangles, circles and so on. Is there an algorithm for this or do I have to do it by myself? |
18 | Z order curve how to query all nearest neighbors? TLDR How to query all nearest neighbors with the least effort? (Iterating over a bigger neighboring area that's continuous and filtering out elements that are not immediate neighbors?) Suppose the following situation You have a set of 3D points' discrete grid locations stored in a 1D array (an OpenCL buffer) You've assigned each point its Z index Morton code You sort the array according the Z indexes You generate a lookup array containing the beginning and end indices of continuous regions of same Z index value particles in the first array Next suppose that you have an OpenCL kernel which executes for each individual particle. And in that kernel you need to loop over all nearest neighboring particles not only grid cells (including the currently processed particle itself) of the currently processed particle (that could be 9 neighbors for 2D case, or 27 for 3D). All of the neighboring particles (for a processed particle) are stored in the nearest neighboring grid cells. Note that the number of particles in one cell can be high (e.g. look at the bottom right cells of the image below). Question How can I iterate through all the neighboring particles (ideally in a continuous manner)? If this couldn't be solved via Z order curve, what other approaches can I use? Example pseudocode kernel void process stuff(...) foreach ( neighboring particles ) lt how to achieve this efficiently? perform computation Image legend Red line Z order curve The blue dot the currently processed particle Yellow dots another particles Green region the current particle neighborhood a set of particles I need to iterate through |
18 | Rotated Sprites collision detection I am trying to implement checkCollision function in my game, I used AABB method but the problem is that my sprites are rotated so it's not really precise. I could finely describe my Sprites with rotated ellipses. Is there any more precise way of detecting the collision if I have the following attributes of entities entity.x entity.y entity.width entity.height entity.angle Here is what I have coded so far (x and y are in the middle of my sprite) this.checkCollision function(entity1, entity2) return (entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 lt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.x (entity1.width this.COLLISION EPSILON WIDTH) 2 gt entity2.x (entity2.width this.COLLISION EPSILON WIDTH) 2 amp amp entity1.y (entity1.height this.COLLISION EPSILON HEIGHT) 2 lt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2 amp amp (entity1.height this.COLLISION EPSILON HEIGHT) 2 entity1.y gt entity2.y (entity2.height this.COLLISION EPSILON HEIGHT) 2) PS my cousin told me to do it with three circles (which creates a shape very similar to the ellipse) but I do not really know how to do it. |
18 | Collision detection in Pong clone Well I'm trying to create a pong clone using SDL and I had some problems with the frames and some times the ball would go through the paddles despite the fact that at other times the collision worked perfectly. So I searched it a bit and I came to the conclusion that it was because in one frame the ball was already through the paddle and in another frame the ball was not or something like this. So thought that if I would manually adjust the position of the ball, like move it a couple of pixels away the moment it hits a paddle or the walls too, this would solve the problem. But now when the ball goes right past a paddle its movement is getting weird and it goes right in the playing field. for reference also some code if you want to look it . I feel bad for doing the whole collision like these but I couldn't think some other way. Please enlighten me if there are better ways to do it that I can avoid the frame problem I mentioned above. Here is the code that handles the ball's movement void Ball move(float xLeftPaddle, float yLeftPaddle,float xRightPaddle, float yRightPaddle, Uint32 deltaTicks) y yVelocity ( deltaTicks 1000.f ) x xVelocity ( deltaTicks 1000.f ) if( y BALL HEIGHT gt SCREEN HEIGHT ) x x 1 y y 1 yVelocity yVelocity else if( y lt 0 ) x x 1 y y 1 yVelocity yVelocity else if(x BALL WIDTH gt xRightPaddle amp amp y lt yRightPaddle PADDLE HEIGHT amp amp y gt yRightPaddle ) x x 1 y y 1 xVelocity xVelocity else if( x lt xLeftPaddle PADDLE WIDTH amp amp y lt yLeftPaddle PADDLE HEIGHT amp amp y gt yLeftPaddle) x x 1 y y 1 xVelocity xVelocity else if(x lt 0 x gt SCREEN WIDTH) x SCREEN WIDTH 2 y SCREEN HEIGHT 2 |
18 | Pygame Error AttributeError 'pygame.Surface' object has no attribute 'add internal' I'm making my first game of Pygame. I'm going to create groups for making collisions but when I add an object to the group, I get an error in sprite.py (Pygame's Files) AttributeError 'pygame.Surface' object has no attribute 'add internal' Why I get this error? There is a simplest way to make collisions? There is my code import pygame from pygame.locals import import sys import os import time width 950 height 500 Game False GameOver False keyboard pygame.key.get pressed() K UP def main() pygame.init() screen pygame.display.set mode((width, height)) pygame.display.set caption('Flappy Dog') background pygame.image.load(os.path.join("Images", "Background 00.png")).convert() FlappyDog pygame.image.load(os.path.join("Images", "Flappy.png")).convert alpha() Play pygame.image.load(os.path.join("Images", "Play.png")).convert alpha() Dog0 pygame.image.load(os.path.join("Images", "Dog0.png")).convert alpha() Dog1 pygame.image.load(os.path.join("Images", "Dog1.png")).convert alpha() SpikeUp0 pygame.image.load(os.path.join("Images", "SpikeUp0.png")).convert alpha() SpikeUp1 pygame.image.load(os.path.join("Images", "SpikeUp1.png")).convert alpha() SpikeDown0 pygame.image.load(os.path.join("Images", "SpikeDown0.png")).convert alpha() SpikeDown1 pygame.image.load(os.path.join("Images", "SpikeDown1.png")).convert alpha() GameOver pygame.image.load(os.path.join("Images", "Game Over.png")).convert alpha() Replay pygame.image.load(os.path.join("Images", "Replay.png")).convert alpha() Bone pygame.image.load(os.path.join("Images", "Bone.png")).convert alpha() Game True Dog1 pos x 100 Dog1 pos y 100 screen.blit(background, (0, 0)) screen.blit(FlappyDog, (0, 0)) screen.blit(Bone, (550, 100)) screen.blit(Play, (600, 350)) screen.blit(Dog0, (5, 240)) bones pygame.sprite.Group() bones.add(Bone) lt Error here Dog pygame.sprite.Group() Dog.add(Dog1) pygame.display.update() while True if GameOver true screen.blit(background, (0, 0)) screen.blit(GameOver, (20, 50)) if pygame.sprite.gropucollide(Dog, Bones, True, True) Game False GameOver True while Game True pygame.event.pump() if pygame.key.get pressed() K UP for i in range(10) Up Dog1 pos y Dog1 pos y 1 screen.blit(background, (0, 0)) screen.blit(Dog1, (Dog1 pos x, Dog1 pos y)) screen.blit(SpikeDown0, (0, 436)) screen.blit(SpikeUp0, (0, 0)) pygame.display.update() pygame.time.delay(1) else Down Dog1 pos y Dog1 pos y 1 screen.blit(background, (0, 0)) screen.blit(Dog1, (Dog1 pos x, Dog1 pos y)) screen.blit(SpikeDown0, (0, 436)) screen.blit(SpikeUp0, (0, 0)) pygame.display.update() pygame.time.delay(1) for event in pygame.event.get() if event.type pygame.QUIT pygame.quit() sys.exit() pygame.display.update() if name " main " main() |
18 | Why does the player fall down when in between platforms? Tile based platformer I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER FRAME event. It's only for collision from the bottom for now. var i int var j int var platform Platform var playerX int player.x 20 var playerY int player.y 20 var xLoopStart int (player.x player.width) 20 var yLoopStart int (player.y player.height) 20 var xLoopEnd int (player.x player.width) 20 var yLoopEnd int (player.y player.height) 20 var vy Number player.vy 20 var hitDirection String for(i yLoopStart i lt yLoopEnd i ) for(j xLoopStart j lt xLoopStart j ) if(platforms i 36 j ! null amp amp platforms i 36 j ! 0) platform platforms i 36 j if(player.hitTestObject(platform) amp amp i gt playerY) hitDirection "bottom" This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great. |
18 | How to check for collisions in "diagonal" tiles? I want to create a tiled map in the following scheme The player should be able to walk on the blue line (street). Now, what is the best way to solve collision detection in this case? For example, in the case of tiles C1 and C2 If I make them walkable, then the player could also move in on those black parts of the tiles that should not be walkable. On the other hand, if I make both C1 and C2 blocked, then the player would not be able to walk on these tiles (and therefore on the street) at all. Any best practices? Thanks. |
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 | 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 | Determine if Plane is seen by Camera If I have an arbitrary plane (center and normal) or a quad (center, normal and width and height) and a camera (frustum, projection amp view matrix, etc). Then how would I go about calculating if the plane quad is visible to the camera? Additionally how would I calculate to check if it's the front or the back of the plane quad that is visible to the camera? My first idea was to do some ray vs plane intersection, but then I realized that it of course wan't going to work! bool plane visible false const float denom plane normal.dot(camera.getLook()) if (abs(denom) gt 0.0001f) const float t (plane position camera.getPosition()).dot(plane normal) denom plane visible (t gt 0.0f) Using the dot product of the plane quads normal and the camera's look direction. Will give wrong results! For instance, use the following image as an example! A dot product will tell me that I'm looking at the face that's facing outwards of the frustum. Though the face that I'm actually looking on is face facing inwards the frustum towards the camera! |
18 | C Monogame Collision Detection Sprite walking through platforms I am blanking on the logic here. How do I get it so that my sprite doesn't run through a block. It only repels if the center of the player sprite is higher than the bottom of the block. But when it is lower, it walks right through. It gets lower because my jump function or my grounded function is a bit funky. Anyway, how do I get it so that a player can't go underneath a block unless the sprite is not touching the block at all. Here is the collision code in my player class, the one that does the collision detection. public void checkYCollisions(block platforms) if (position.Y gt 700) this is my ground with no blocks. grounded true else grounded false float Xradius Width 2 float Yradius Height 2 block collidedPlatform null List lt block gt collidedBlocks new List lt block gt () foreach (block p in platforms) if ((position.X gt (p.position.X p.Width 2 Xradius )) amp amp (position.X lt (p.position.X p.Width 2 Xradius )) amp amp (position.Y gt (p.position.Y p.Height 2 Yradius )) amp amp on top (position.Y lt (p.position.Y p.Height 2 Yradius ))) below collidedBlocks.Add(p) collisions work for all side of blocks. foreach (block p in collidedBlocks) if (p ! null) if ((position.Y lt (p.position.Y p.Height 2 radius ))) landing on a block grounded true else if ((position.Y gt (p.position.Y p.Height 2 Yradius ))) jumping up into a block if (y vel lt 0) y vel 1 player1.direction.Y 1.0f player1.direction.Y else if ((position.X lt (p.position.X p.Width 1.5 Xradius ))) one of the sides x vel 2 else if ((position.X gt (p.position.X p.Width 1.5 Xradius ))) other side x vel 2 Note that I have tried to remove YRadius in the the if loops at separate occurences, and it works to no avail because my guy will not hit the ceiling. |
18 | Move collider along with model with Mecanim jump animation I've been creating an infinite runner game in Unity3D for a while and I got stuck in this point that whenever my character jumps using Mecanim system his model (mesh) goes to air but his attached collider does not. For jumping I don't apply any force or somethings else. (He does not even have a rigid body component). The jumping process is only done by Mecanim animation jump. Is there any way to make that collider to move along with the model? Please note that since I've used character controller to controlling my character, I cannot use "Apply root motion". |
18 | javascript efficient collision detection I have a processing game where I am having serious lag problems with collision detection. I am using the most effective code I can think of however after about 9 levels in The game gets unbearably laggy. I would show you the code but site wont handle my less thans. If you want to check the program out you can find it here https www.khanacademy.org computer programming tanks v1245 6637554186715136 under the tankMelee function line 160 |
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 | Different bounding volumes for culling and collision detection Should an object in a 3D engine use different bounding volumes for collision detection (broad phase) and culling? Basically class renderBounds and class physBounds versus class boundingVolume? Each of this classes then could either contain the same type of volumes (AABB's, kDOP's, sphere's etc.) or a special fitting one for the particular object. (note without considering of using an external physics engine) |
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 | 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 should I choose quadtree depth? I'm using a quadtree to prune collision detection pairs in a 2d world. How should I choose to what depth said quadtree is calculated? The world is made mostly of moving objects1, so the cost of dispatching the objects between the quadtree cells matters. What is the relationship between the gain from less collision checking and the loss from more dispatching? How can I strike a balance that performs optimally? 1 To be completely explicit, they are autonomous self replicating cells competing for food sources. This is an attempt to show my pupils predator prey dynamics and genetic evolution at work. |
18 | Calculate point of circle circle collision between frames I need to find the exact XY coordinate where a circle collides with another circle calculated between frames. This means that I take the coordinate of the moving circle on the previous frame and take its coordinate on the current frame. Then I need to find the position where the circle collides some time along this line segment. In the diagram below, the blue circle moves from the previous frame (upper) to the current frame (intersecting, lower). During this time it would have hit where the dashed circle is. I need to find the coordinate of the green point. Also note that it may be possible for the blue circle to entirely pass through the red circle. There would then be two points, so the first must be used. |
18 | Implementing Separating Axis Theorem to Detect and Handle Sliding Collisions I am having a bit of difficulty detecting collisions properly with separating axis theorem. My code seems to be giving a lot of false alarms. Also, I've looked into implementing sliding collisions with the data from the theorem. This is the resource I used for this algorithm https stackoverflow.com questions 115426 algorithm to detect intersection of two rectangles?rq 1 This is my code for detecting collisions Note .boundingBox is a set of four vertices for each rectangle. It is Bottom Right, Bottom Left, Top Left, Top Right Also .edge is the set of four edges for each rectangle. It goes Bottom, Left, Top, Right Only take two edges of each rectangle since two edges share each axis var edges this.edges.slice( 0, 2 ).concat( polygon.edges.slice( 0, 2 ) ) Loop through the axes of both rectangles for ( var i 0 i lt edges.length i ) var oppositeSides true, Convert the edge to an axis by finding its normal, then convert the axis to a unit vector magnitude i 2 0 ? 50 25, normal x edges i .y magnitude, y edges i .x magnitude , Take one point on the current shape and find its projection onto the axis currentPoint i lt 2 ? this.boundingBox i polygon.boundingBox i 2 , nextPoint i lt 2 ? this.boundingBox i 2 polygon.boundingBox i , shape1Vector x nextPoint.x currentPoint.x, y nextPoint.y currentPoint.y , shape1DotProduct shape1Vector.x normal.x shape1Vector.y normal.y, shape1DotProductSign shape1DotProduct gt 0 Take all the points on the other shape and project their distance onto the axis. If their dot product sign is opposite to the point on the same shape, then there must be no collision for ( var j 0 j lt 4 j ) nextPoint i lt 2 ? polygon.boundingBox j this.boundingBox j var shape2Vector x nextPoint.x currentPoint.x, y nextPoint.y currentPoint.y, , shape2DotProduct shape2Vector.x normal.x shape2Vector.y normal.y, shape2DotProductSign shape2DotProduct gt 0 if ( shape2DotProductSign shape1DotProductSign ) oppositeSides false if ( oppositeSides ) return true return false Now for handling the sliding collisions, I attempted to project the rectangle's velocity vector onto the axis where there is the least overlap, then multiply that scalar dot product by the unit vector of the axis, but that seems to result in strange behaviour where the velocity goes to insane velocities. |
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 | Is there a name for this algorithm for 2d shape collision? A while ago I was considering my possibilities for implementing collisions between 2D shapes, and after much googling (which mostly turned up SAT), I came up with this let A, B two shapes let V Speed of A relative to B for a point in vertices of A for b segment in segments of B if segment(a, a V) intersects b return intersection point return false Now, I'm far from the smartest person out there, so I am 99.8 sure someone must have come up with that before me and, what's more important, since I didn't find anything describing this method, I assume it's a bad one. Can anybody identify this algorithm and or point me towards any literature on it explaining if, when and why it should be used? I've failed to see any significant problems at first sight all the complex calculations can be hoisted outside of the loops and then it's just matrix multiplications within both loops, and I couldn't find any algorithm that makes do without any nested loops over two sets of elements (be they vertices, segments or normals) Feel free to trash talk my algo all you like, I never expected it to be the second greatest discovery right after general relativity or anything ) PS Sorry for the poor title, but I can hardly explain the entire algo in one line ) |
18 | Bounding box of a rotated rectangle (2d) I can see this has been asked before in various ways. I am struggling to work it out though hence asking again. 2d sprite that moves and rotates. I'm looking to contain it in a bounding box as it appears that is the most efficient way to do collision detection. I had no problems getting it to work without rotation but that is simple! Now the sprite rotates I can't seem to find the right way of writing the code. To create a bounding box for the sprite, my understanding is I need to work out the 4 corners of the sprite after rotation and use these to work out the width height of the correctly sized bounding box. I've used the article here http msdn.microsoft.com en us library dd162943(v vs.85).aspx specifically the formula x' (x cos A) (y sin A) y' (x sin A) (y cos A) The code I'm currently using x1 (positionX Math.cos(rotation)) (positionY Math.sin(rotation)) y1 (positionX Math.sin(rotation)) (positionY Math.cos(rotation)) x2 (positionX width 2 Math.cos(rotation)) (positionY height 2 Math.sin(rotation)) y2 (positionX width 2 Math.sin(rotation)) (positionY height 2 Math.cos(rotation)) positionX and positionY is the current top left hand corner position of the sprite. rotation is the radians the sprite has been rotated by (and rotation is from the centre). width and height are of the sprite. I thought the code above would give me the co ordinates of the top left and top right corners of the rectangle, rotated appropriately. However, on my canvas, I'm drawing a line from x1,y1 to x2,y2 and it doesn't follow the sprite at all! Any suggestions? Sorry for the long post! Cheers! |
18 | Moving OBB vs. triangle intersection test Requirements to write a test function that, given a moving OBB (oriented bounding box) and a triangle, returns true whenever the OBB hits the triangle. The OBB is described by its half extents (h1, h2, h3), principal axes (a1, a2, a3) and center point C(cx,cy,cz). The triangle is described by its three vertices (U1, U2, U3). The OBB moves with the velocity V over a period of time of 1 second (hence V is also the displacement the OBB undergoes). Question I have already read Dave Eberly's mini paper on the matter and made an attempt at an implementation. Also related to this paper, I have a question regarding the w projection of the W velocity is w equal to dot(W, L), where L is one of the 13 possible separating axes he considered in that paper? |
18 | How can I implement bounding volume subdivision for my sprite images? Lately, I have been researching different Collision methods, how to deal with multiple collisions and different types of bounding shapes, circles, rectangles, polygons and ellipsoids. Some common collision methods are the 'Axis aligned bounding box' if (rect1.x lt rect2.x rect2.width amp amp rect1.x rect1.width gt rect2.x amp amp rect1.y lt rect2.y rect2.height amp amp rect1.height rect1.y gt rect2.y) collision detected! 'Circle Collision' double dx (circle1.x circle1.radius) (circle2.x circle2.radius) double dy (circle1.y circle1.radius) (circle2.y circle2.radius) double distance Math.sqrt(dx dx dy dy) if (distance lt circle1.radius circle2.radius) collision detected! The bounding box shape dilema For one my projects, I am using images, which are rectangle by nature. However, to simply check for intersections with the images' edges would result in unsatisfactory collision detection. As Gamasutra puts it " The experience of playing some of the early flight simulators illustrated how bad collision detection can ruin a game. Flying through a mountain peak and surviving isn t very realistic. Even some recent games have exhibited collision problems. Many game players have been disappointed by the sight of their favorite heroes or heroines with parts of their bodies inside rigid walls. Even worse, many players have had the experience of being hit by a rocket or bullet that was not even close to them. " From that resource I discovered an interesting method of making bounding boxes or circles which Gamasutra calls subdivision I am having trouble thinking how to do this subdivision process for my images (as I am working with images) and how to properly implement either subdividing process within my collision reliant app. For example take mario and a koopa shell. I wouldn't want their transparent space to trigger intersection |
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 | Find the Contact Normal of Rectangle Collision It seems a lot of people have asked similar questions on this site, and every time it seems like a whole bunch of answers that don't work are given. Basically, I have two rectangles (AABBs) that collide, and I want to find out on what side they collided with each other. I know the velocities of each object before they collide, and of course their positions before and when they've actually collided (if I use discrete collision checking that is, currently I'm using speculative). Many people say find the lowest penetration distance or take the largest speed (either horizontal or vertical) and that will give you the answer. But the collision is dependent on both of those values, I just don't know how they fit together to tell me where the collision is coming from. I don't think I need an exception for corner collisions. I do not want to do my horizontal and vertical collisions separately as that just opens up even more problems. So, any suggestions? |
18 | How can I create a set of collision points for an arbitrary mesh? In my project I am working on automatically deforming an arbitrary mesh with respect to another arbitrary mesh, within the context of user generated content, similar to this deformer being developed for Second Life. In order to preserve the features of a deformed mesh, which may consist of things such as 'folds' for the edge of the mesh, I would like to deform my target with a set of deformers, however defining an appropriate set of deformers has given me trouble and I think now the best way to do it is to create a 'collision mesh' set of 'control points'. These points will proxy for the target mesh in collision detection and define the deformers used to deform the main mesh. Since I generate it its structure can be more tightly controlled. I want to create a 'grid' of points which approximate the surface of my mesh, like the control points on a NURBS surface. I was thinking of a technique with principles like those used in the layered depth image technique here, but wondered if there was already a good existing solution for what I want to do? What is the most effective way to create something that approximates a collision mesh for an arbitrary mesh automatically? |
18 | Error detecting collision with another instance of the same actor? I have a project where after a certain time interval 2 NPCs are generated in different locations on the map. Each of them collides with a collision box that defines its "class" (red or blue) When 2 NPCs collide it was to be verified a condition (if the "class" of the involved ones is different) and from there both are destroyed, but nothing happens I put a print right after the Cast To NPC to see if it was happening and when they are generated the impression appears four times. Blueprint Result in game I'd like to know how to set a cast only between two instances of the same actor. Image showing that nothing happens when it (two instances of the same actor) collide I did the test with both codes (printing and destroying both). EDIT 1 (I was being redundant) In the code of destruction, I can simply put it to destroy itself only, because as it will run in both instances, the two will destroy themselves I'd still like to know how to correctly detect the collision between two instances of the same actor, but now I know that the code will be running twice, once in instance A and again in instance B. |
18 | Should I do intersection testing in world or object space? I'm adding basic ray casting and collision detection for my game, and also adding bounding volumes and collision meshes. The ray is cast in world space and each mesh's node can track its world transformation. Considering I want to test for intersection between a ray and bounding volume and also bounding volume with other bounding volume, in what space should I perform the intersection test? Scenarios that I have in mind Transform ray into object's local space, perform test, then inverse transform the resulted point. Transform bounding volume into world space and perform it there, or should I always keep bounding volumes in world space? Perform bounding bounding test in world space or one of the objects? Do things change much between static and dynamic collision regarding used spaces? |
18 | Check if a point is touching a user drawn curve in HTML5 canvas I am having trouble detecting whether a ball is colliding with a red curve. The curve below is an example of what a user may draw on to the canvas. I can't think of any fast ways to detect collision between a green ball and the red line here. I have thought of checking the color of the pixel every tick at the location of the ball, but this is very slow and the round ball will fill more than just the centre pixel. I have also thought about logging every single X, Z point that the curve drawer has inserted and then checking if the ball is near to the point, but this also seems like a bad method. From a red curve drawn on to the screen by a user, what is the best way to detect whether a point is colliding with the red line? Shall I store every single point of the red curve or check the color of the pixel at the point to see if it is red or not? |
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 | How do I convert OnCollisionEnter2D to OnMouseDown? I created a simple animation. I have a "Gamer" object, which I move and hit squares to destroy them. Squares I have to destroy in the right order (1 2 3 4 5 etc.) If I make a mistake, the animation comes to an end. However, I would like to change this code now. I would like to change OnCollisionEnter2D() on OnMouseDown(). I would like to continue to delete the squares one by one, but instead of using a collision simply click on the squares. Could anyone help you convert this code? This is my code posted to the "Gamer" object using System.Collections using System.Collections.Generic using UnityEngine using UnityEngine.SceneManagement public class Gamer MonoBehaviour int index 1 public GameObject gameOverText, restartButton public GameObject WinningText, ExitButton, NextLevelButton public GameObject Manager void Start () gameOverText.SetActive (false) restartButton.SetActive (false) Manager.SetActive (true) WinningText.SetActive (false) ExitButton.SetActive (false) NextLevelButton.SetActive (false) public void OnCollisionEnter2D (Collision2D col) Debug.Log("Player hit object " col.transform.name) check if the object you hit is one of the "collisionObjects" if(col.transform.GetComponent lt collisionObject gt ()) GetComponent lt AudioSource gt ().Play() collisionObject colObj col.transform.GetComponent lt collisionObject gt () if(!colObj) return if(index colObj.myIndexNumber) if (colObj.isHighestNumber) Debug.Log ("Yay you correctly hit the last Square, You WIN!") WinningText.SetActive (true) NextLevelButton.SetActive (true) ExitButton.SetActive (true) gameObject.SetActive (false) Manager.SetActive (false) Destroy(col.gameObject) index here, we know it didn't match the number. ) else gameOverText.SetActive (true) restartButton.SetActive (true) gameObject.SetActive (false) Manager.SetActive (false) And this is my code placed in the "square" object using System.Collections using System.Collections.Generic using UnityEngine public class collisionObject MonoBehaviour public int myIndexNumber public bool isHighestNumber public void Start() isHighestNumber true find all other objects foreach (collisionObject cObj in GameObject.FindObjectsOfType lt collisionObject gt ()) check if any of the other objects has a larger number than mine, if yes, note to self that i am not the highest number. if (cObj.myIndexNumber gt myIndexNumber) isHighestNumber false break Debug.Log("Object number " myIndexNumber " is here is highest Number " isHighestNumber) |
18 | simple solution for 3d collision detection and response I'm having great difficulty trying to implement collision detection and response in a 3d game What are some simple solutions someone can use to implement smooth collision and response similar to games like Quake? I can see there are a lot of different ways to do collision and response but that makes it even more confusing, Im not sure which method is the best solution to sit down with. So I was wondering what is the goto solution for the average programmer? All I have found online are very complicated incomplete mathematical explanations which I have a hard time understanding. Is this really a topic that requires an entire textbook to understand?? Perhaps theres a library ? Ive tried looking into bulllet but it seems to require heavy knowledge of physics. The best solution I have found is in a software called darkbasic, where it somehow handled sliding collision automatically and all the user had to do was desginate which object were to be handled. Was wondering maybe theres something similar to that |
18 | Unity, changing gravity game stopping character when he hit a wall I am currently working on a 2d puzzle game in the unity engine. One of the aspect of this game is the possibility to rotate the level of 90 . It also rotate the gravity. The main character is not directly controlled by the player, but instead falls when the level is rotated. When the main character hits a wall, he should stop to moving. If I do not stop it, it kind of blinks and shakes against the wall. To stop it I detect collision and depending on the current rotation state, the player will stop at "vertical" or "horizontal" tags when a OnCollisonEnter occurs. I must do that because when the player falls on his relative ground, he must not stop like if he had touched a wall. My problem is the 'side' of platform, or the 'top' of wall, they use the same tag and thus do not give the correct tag to my character. I tried to put a very small invisible box on top side of elements but the collision occurs nevertheless. It seems when the player falls and hit something he go through a bit before being replaced at correct position by unity. Is there a way 1 ) to not stop my character but to make it appear immobile on screen 2 ) To detect a "I cannot move anymore" collision other than by using collision? |
18 | How to detect collision with non rectangular objects in 2D games? Detecting collision with rectangular objects is quite easy. I am able to write simple tile based games. Now I want to learn to write non tile based games in which objects may not be rectangular, for example, a mountain. Suppose I want an uneven terrain with hills and mountains how do I store the shape of the terrain? Also how do I detect the collisions for such uneven objects? |
18 | Finding the point of collision I'm writing a 2D rigid body simulator. The objects being simulated are convex polygons. My question involves how to decide on the "point" of collision, so that when I apply a response force, I can also calculate torque. In 2D, the popular method of narrowphase collision detection seems to be the Separating Axis Theorem. However, while this gives you the "are they colliding?" as well as "by how much?", it does NOT give you a reference point (that I'm aware of) at which to apply the response force (and thus calculate torque) . The other method (which also interests me more, because it's what's used in 3D, which would be the logical next step) is to calculate the Minkowski difference of the two polygons, and decide that they're colliding if (0,0) is contained in the resulting polygon. But, how do you use this to decide the relative point at which to apply the response force? My hypothesis is that, since each face of this difference effectively corresponds to a face of one of the polygons, the separation distance is the shortest distance from (0,0) to the MD, and you apply this to the corresponding face on the polygon. As a bonus, how does one do this in 3D? As I'm writing this, I just realized that, when using SAT, I could just keep track of which points are overlapping, and apply the force at the "average" of those points. But I would have to decide on which of the several non separating axes to perform this little trick... |
18 | 2D games on Unity and collision detection performance I'm developing a 2D game for the iOS platform. I have seen a lot of packages on asset store that makes 2D asset creation for unity easier. I have narrowed my selection to just 2, 2d toolkit and ex2d. I have to test them and see with fits my workflow better (if anyone has an useful opinion I'm all ears). But my main concern is how to do the collision detection in unity for this kind of games. My game is a side scroller and I want it to have slopes. I have done this in my own engines using tile height maps, etc... but unity doesn't support all this, but it has a physic engine. Do you think unity own physics engine will be ok for a game like this? I really need a good control on player collision to achieve a nice playability, so, I'm a bit sceptic if I will be able to do it using the physic engine, perhaps, because of my poor knowledge on this subject. I have thought about rolling my own 2D cuad collider and do my own collision detection on the fixed update call but not sure either if it will be faster that the built in physics engine because unity3d could be just optimised to use its own collision system. What do you think? |
18 | Why do restitution values less than one still cause infinite bouncing in Box2D? I'm currently trying to implement basketball bouncing into my game using Box2d (jBox2d technically), but I'm a bit confused about restitution. While trying to create the ball in the testbed first, I've run into infinite bouncing, as described in this question, however obviously not using my own implementation. The Box2d manual describes restitution as follows Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. My confusion lies in that I am still getting infinite bouncing with restitution values at 0.75 0.8. The same behavior can be seen in the testbed under Collision Watching Varying Restitution, on the 6th and 7th balls. I believe the last one has restitution of 1, which makes sense, but I don't understand why the second to last ball bounces infinitely (as is happening with my working basketball I've created). I am looking to understand the restitution concept more fully, as well as look for a solution to infinite bouncing with the Box2d framework. My instinct was to sleep objects that appeared to be moving in very small increments, but this seems like a misuse of the engine. Should I just work with lower restitution values altogether? |
18 | Ball vs 45 degree slope collision detection I have a simple game in which the player moves a ball around. The ball bounces off of walls. Right now I have square walls( ) implemented I use simple bounding box collisions to check if the player will move into a wall when updating its x or y speed and if so, I multiply that speed with 1 to make them bounce. However, I also want to implement triangular pieces( ). To bounce back I believe one can simply use newxspeed 1 yspeed newyspeed 1 xspeed However, what I am having trouble with is the collision detection When does the player hit the diagonal? |
18 | 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 | Collision detection between image and drawables I'm trying to collide my ball 1 to greengreen drawable. How can I determine the collision? public class MainActivity extends Activity implements Runnable private Imageview ball1 Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState) setContentView(R.layout.activity main) ball1 (ImageView) findViewById(R.id.ball 1) Drawable gr1 new Drawable(R.drawable.greengreen) public void run() startballanimation() try Thread.sleep(1000) catch (InterruptedException e) e.printStackTrace() trying to use an if else statement here to collide imageview ball1 to drawable"greengreen" |
18 | 2D Collision detection and design So, listening to this very smart piece of advice, I've already completed a basic Tetris game. Moving on, I started a small breakout. But suddenly a nightmare came. Collisions. Since I've been struggling with this a lot, I read a bunch of article of the web. Being a beginner, I thought that, in the first approach, I would only use Rectangle to detect collisions. Right. Now I still have some problems. First of all, all the articles I stumbled upon on the Internet told me how to detect collisions, e.g. checking if objects A and B collided with each other. But it is not what I really need. In order to respond properly, I need to tell my objects if the collision happened on the X or Y axis and then setting the new velocity according to some rules. The problem is that there are so many possibilities when making the distinction between types of collisions that I don't think I've taken the right path. The second point (which, I believe, is really tied with the first) is the pattern in which the detection and the resolution of a collision happen. Right now, I have a CollidableObject classes and a CollisionDetector classes which knows about these objects. Each frame, the detector is looking for collision (or at least for me, is trying) and when he finds one, it alerts each collided object, saying "Hey you ! You've have collided with Z on the X axis, change that velocity now." and the object abides. The main issue right now is that I can detect the collision axis and therefore, when saying "Hey you ! You collided !", I cannot respond properly. In which direction should my velocity change ? I've been thinking a lot about this lately, trying to figure it out on my own, but I haven't find something that I liked so I am asking here now. Thank you for your answers ! (Note I don't know if this is relevant, but I'm coding in C using SDL) |
18 | Automatically generate low detail collision meshes I lately integrated Bullet Physics into my little game engine, but for now I only use basic shapes as spheres or boxes for collision checks. For more realistic physics I need collision meshes for all models in the scene. They should be much simpler and in lower detail than the actual model for drawing to speed up computations. Since I want adding new asserts to the engine as easy as possible, I am looking for a way to automatically generate collision meshes. I could just use the actual mesh loaded from file and that would result in very realistic physics calculations but that won't be fast enough. Therefore, how can I generate low detail collision meshes from a given set of vertices? This task doesn't seem trivial since there many different cases to handle. For example a model of a house with furniture must retain details of floor and door frames while ornaments should be removed. I believe there already was research on this topic, but I couldn't find anything useful yet. |
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 | 3D models and hit detection I'm currently trying to create a game that involves the inside of a cube, which i will make in Maya. My question is what is the best way to create a model with hit detection in mind? For example my model will be a cube that you can walk inside of, so should i make the cube as a one model or make one wall and put it together inside XNA? The reason I ask this is because I'm sure that if I create a whole cube and then use XNA's bounding rectangle method, hit detection will always be true because the bounding rectangle will encompass the whole cube, making collision detection inside the cube non existent without the use of hard values. Whereas separate walls would make the process easier because i will checking against separate walls instead of the whole thing. To add to the problem, I also have doors in the walls so hit detection for the walls in that area need to be turned off. What is the best way to do this? |
18 | Collision detected on only the latest added tile I'm making a 2D platformer and I'm using tiles as the ground. I have a Tile class and I'm loading the tiles with the help of a list in the main game class public static List lt Tile gt tiles new List lt Tile gt () The following is how I load the tiles from the list with 2 for loops in the LoadContent method for (int i 0 i lt 20 i ) tiles.Add(new Tile(Content.Load lt Texture2D gt ("tile"), new Vector2(i 16, 304))) for (int i 0 i lt 10 i ) tiles.Add(new Tile(Content.Load lt Texture2D gt ("tile"), new Vector2(i 16, 288))) Now, I wanna apply some kind of gravity and collision, still it's just something primitive. I'm applying these inside a Player class within a foreach loop like this foreach (Tile tile in Game1.tiles) if (isInAir true) velocity.Y 100f else velocity.Y 0f if (recBot.Intersects(tile.rectangle)) colBot true else colBot false if (colBot true) isInAir false else isInAir true The issue is that the collision occurs only on the last loaded tile by the for loop in the LoadContent method. The sprite stops falling when it collides with the last added tile, but when I'm moving left or right and it intersects with other tiles, it doesn't apply the collision and it falls through them. I'm kinda new to programming, so take me easy ) Any other things that you need to know, just tell me and I'll add more details or code! |
18 | Do I need to roll my own polygon segmentation algorithm to automate Box2d body creation from a tile map? Before re inventing the wheel I figured I'd ask I'm working on a tile based 2d maze level generator for cocos2d box2d. The idea is I'm using one of the well known graph traversal algorithms to generate a random maze. This data gets encoded as an XML of the type that both Tiled and cocos2d can work with. Based on the generated maze tile data, my program should also generate the polygonal data (vertices) that define the walls of the maze so that I can get them from, for instance, a Tiled's XML's object layer and into Box2d for defining bodies. However, I'm at step 3 and so far, I'm thinking of solving this step with something along the lines of a flood segmentation magic wand algorithm. That is, from step 2 I get the graph's nodes which translate in Tiled's XML to, for instance, a 2d array where walls are marked with a number and open spaces are 0s. This is in the cvs non compressed XML representation for instance. So what I need to do now is sort of solve the convex hull problem for a bunch of points (the non zero numbers in this 2d array), but actually creating different polygons. I also need to then break any concave ploys into convex, but that can be done easiest with ear clipping and, should I decided to get fancier, Delaunay or something. Let me illustrate with images And in the next image you can see A the set's convex hull (approximately), and B what I'm trying to achieve (concave subsets of the hull) That is, I need to be able to distinguish separate polys. Of course, but for one, these also turn out to be concave which Box2d will not like. But like I said, I'll turn them to convex sets afterwards. The question is, is there anything built in or tested tried that I could just grab and use or do I need to implement my magic wand algorithm? I'm also open to different approaches all together. |
18 | Pygame CollideRect But How Do They Collide? I'm having some trouble figuring out how I can handle collisions that are specifically colliding on the top or bottom a rect. How can specify those collisions? Here's a little code snippet to give you an idea of my approach. As it is now it doesn't matter where it collides. the ball has hit one of the paddles. send it back in another direction. if paddleRect.colliderect(ballRect) or paddle2Rect.colliderect(ballRect) ballHitPaddle.play() if directionOfBall 'upleft' directionOfBall 'upright' elif directionOfBall 'upright' directionOfBall 'upleft' elif directionOfBall 'downleft' directionOfBall 'downright' elif directionOfBall 'downright' directionOfBall 'downleft' Thanks in advance. EDIT Paddle rect top Sides bottom I need to know if the ball has hit either the top or the bottom. |
18 | How to place an object so that it does not overlap the objects in my scene? In my game, the user has to click at a point to place an object (mesh). I can cast a ray and find the horizontal point where the object can be translated and then attached to rootNode to display it. However, the problem is that if the user click too near to another object scene wall the object to be placed, runs into it. How can I prevent that? |
18 | 3D Binary Space Partitioning with solid empty leaves I've recently started looking into BSPs for real time collision detection, and I'm now looking into improving the performance of my solution. The system that I've implemented is rather similar to the solution found on wikipedia (https en.wikipedia.org wiki Binary space partitioning), where each node contains triangles found located on the node's hyperplane, and references to two nodes found on each side of the hyperplane. BSP generation pseudocode Node generate bsp(Trimesh mesh) Trimesh back, front Node node(mesh 0 ) Generates the plane position and normal of the node loop (Triangle tri mesh) if (onPlane(tri, node)) node.triangles.add(tri) else if (inFront(tri, node)) front.add(tri) else if (Behind(tri, node)) back.add(tri) Not fully in front or behind means that the triangle is found on both sides and needs to be split else Triangle trisSplit tri.split(node) loop (tri2 trisSplit) if (inFront(tri2, node)) front.add(tri) else if (Behind(tri2, node)) back.add(tri) node.nodeBack generate bsp(back) node.nodeFront generate bsp(front) return node This means that for a raycast, I iterate over the hyperplanes sorted from front to back, and determine if my ray hits any of the triangles found on each hyperplane. BSP raycast pseudocode Bool ray intersect bsp(Vector rayPos, Vector rayDir, Node BSP) if (BSP null) return false if (onPlane(rayPos, node)) if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true else if (inFront(rayPos, node)) if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true else if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true return false This system however demands using ray triangle intersection determination, which is a costly procedure. What makes matters worse is that there's a high chance that the triangles you iterate on are missed by the ray, which results in a relatively large amount of costly raycasts that need to be performed before finding the closest hit on the trimesh. What methods can I use to optimize my BSP structure and traversal? |
18 | How can I optimise collision checks for a large number of AI units? Let's say I got 100 Orcs in my 3D world and they all aim to kill each other. That means for every 1 Orc I have to check for collision with the 99 others. That will give me 99 2 which is about 10,000! That many collision checks every update (24 60 times a second) only for the AI will probably use my whole GPU CPU. How can I handle such a large number of AI? How is this is done in games with large numbers of NPCs (e.g. Skyrim, Fallout, Red Dead Dedemption...). |
18 | Meaning of offset in pygame Mask.overlap methods I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges. It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall. Here is the conceptual image it I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand. Here are the docs for the method Mask.overlap Returns the point of intersection if the masks overlap with the given offset or None if it does not overlap. Mask.overlap(othermask, offset) gt x,y The overlap tests uses the following offsets (which may be negative) .. A yoffset .. B xoffset |
18 | Bounding Box Collision Glitching Problem (Pygame) So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better). Here's the whole code from pygame import DONE False screen display.set mode((1024,768)) class Thing() def init (self,x,y,w,h,s,c) self.x x self.y y self.w w self.h h self.s s self.sur Surface((64,48)) draw.rect(self.sur,c,(self.x,self.y,w,h),1) self.sur.fill(c) def draw(self) screen.blit(self.sur,(self.x,self.y)) def move(self,x) if key.get pressed() K w or key.get pressed() K UP if x 1 self.y self.s else self.y self.s if key.get pressed() K s or key.get pressed() K DOWN if x 1 self.y self.s else self.y self.s if key.get pressed() K a or key.get pressed() K LEFT if x 1 self.x self.s else self.x self.s if key.get pressed() K d or key.get pressed() K RIGHT if x 1 self.x self.s else self.x self.s def warp(self) if self.y lt 48 self.y 768 if self.y gt 768 48 self.y 0 if self.x lt 64 self.x 1024 64 if self.x gt 1024 64 self.x 64 r1 Thing(0,0,64,48,1,(0,255,0)) r2 Thing(6 64,6 48,64,48,1,(255,0,0)) while not DONE screen.fill((0,0,0)) r2.draw() r1.draw() If not intersecting, then moves, else, it moves in the opposite direction. if not ((((r1.x r1.w) gt (r2.x r1.s)) and (r1.x lt ((r2.x r2.w) r1.s))) and (((r1.y r1.h) gt (r2.y r1.s)) and (r1.y lt ((r2.y r2.h) r1.s)))) r1.move(1) else r1.move(0) r1.warp() if key.get pressed() K ESCAPE DONE True for ev in event.get() if ev.type QUIT DONE True display.update() quit() The problem In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast. In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them. The code problem illustrated When the player goes towards the wall (Fine). When the player goes towards the wall and press the opposite direction. (It glitches through). Here is the logic I've designed before implementing it I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching possibilities. What do you suggest? |
18 | Collision detection with heightmap based terrain I am developing a 2D tank game. The terrain is generated by Midpoint Displacement Algorithm, so the terrain is represented by an array index gt height of terrain 0 gt 5 1 gt 8 2 gt 4 3 gt 6 4 gt 8 5 gt 9 ... ... The rendered mountain looks like this 0 1 2 3 4 5 ... I want tanks to be able to move smoothly on the terrain (I mean tanks can rotate according to the height when they move), but the surface of the terrain is not flat, it is polygonal. Can anyone give me some help with collision detection in this situation? Thanks in advance. |
18 | Using max for entry time in swept collision I was reading this tutorial on swept AABB collision detection, and I was confused by this piece of code find the earliest latest times of collision float entryTime std max(xEntry, yEntry) float exitTime std min(xExit, yExit) The tutorial says this about this code entryTime will tell use when the collision first occurred and exitTime will tell us when it exited the object from the other side. This can be useful for certain effects, but at the moment, we just need it to calculate if a collision occurred at all. So if entryTime is supposed to be the first time a collision occured, then why is max being used to determine the first time of collision? Shouldn't min be used instead? If max is used, then the highest value will be returned. The highest value would be the time of the last collision. Obviously this must be the correct way of doing this, but I'm not understanding it. If you are trying to find the first axis to collide, it would seem intuitive that you use min. |
18 | Handling collisions with objects that use vector of unique pointers pragma once include "Entity.h" include lt iostream gt class Projectile public Entity public Projectile() Projectile(float x, float y) load("Graphics Projectile.png") m sprite.setPosition(x, y) m speed 400 pragma once include "Entity.h" include lt iostream gt include "Projectile.h" enum class Color red, yellow, brown, blue class Enemy public Entity public Enemy(const Color amp c, const sf Vector2f amp pos) switch (c) case Color blue load("Graphics blueEnemy.png") break case Color red load("Graphics redEnemy.png") break case Color yellow load("Graphics yellowEnemy.png") break case Color brown load("Graphics brownEnemy.png") break setPos(pos) m speed 100 pragma once include "Entity.h" include "Projectile.h" include lt vector gt class Spaceship public Entity public Spaceship() void move(float) void shoot(float) void update(float) void draw(sf RenderWindow ) override private bool wasSpacePressed std vector lt std unique ptr lt Projectile gt gt m projectiles sf Clock m clock class EnemyFleet public Entity public EnemyFleet() EnemyFleet() void move(float) bool isEnemyBottom() const bool isLeftMost() const bool isRightMost() const void moveX(float) void moveDown() void update(float) void draw(sf RenderWindow ) override private std vector lt std unique ptr lt Enemy gt gt m enemyFleet bool m leftToRight motion of the enemyfleet float m speedModifier I want to be able to delete a projectile and enemy when they collide with each other, but I'm not sure how to do this since unique ptr cannot be copied into any parameter in some collision manager class bc it has exclusive ownership. Is unique ptr still something i should use bc i dont have to call delete (like if its a raw ptr)? |
18 | Detecting collision between a sprite and many tiles I have been looking at the following question Tile coordinates and am thinking of using this for collision detection in my tile game. The set up in my game is similar to this, in that there is a grid of tiles, and the sprite will move to (x,y) coordinates. However, if I were to have an object such as a box in my world that is made from multiple tiles, how would I get the collision detection to work? Any ideas welcome. |
18 | 2d Circle different ARC's Collision detection I've read about the way to detect collision between 2 circles or circle and line using trigonometry. But now I would like be able to detect which part of the circle arcs I'm hitting. For example I divided my circle to 4 different sized arcs. I would like to know which arc gets hit, 1, 2, 3, or 4? See image What is the best collision detection algorithm for this? Or what is this called? |
18 | Collision detection recommendations I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around. I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use. For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen. Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects. My game be 2D and will use a top down ortographic projection and I am developing it using Cocos2d X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior). |
18 | Change collision action I have a collision detection and its working fine, the problem is, that whenever my "bird" is hitting a "cloud", the cloud dissapers and i get some points. The same happens for the "sol" which it should, but not with the clouds. How can this be changed ? ive tryed a lot, but can seem to figger it out. Collision Code (void)update (ccTime)dt bird.position ccpAdd(bird.position, skyVelocity) NSMutableArray projectilesToDelete NSMutableArray alloc init for (CCSprite bird in projectiles) bird.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(bird.position.x, bird.position.y, bird boundingBox .size.width, bird boundingBox .size.height) NSMutableArray targetsToDelete NSMutableArray alloc init for (CCSprite cloudSprite in targets) cloudSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(cloudSprite.position.x, cloudSprite.position.y, cloudSprite boundingBox .size.width, cloudSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , cloudSprite boundingBox )) targetsToDelete addObject cloudSprite for (CCSprite solSprite in targets) solSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(solSprite.position.x, solSprite.position.y, solSprite boundingBox .size.width, solSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , solSprite boundingBox )) targetsToDelete addObject solSprite score 50 2 scoreLabel setString NSString stringWithFormat " d", score N R SKYEN BLIVER RAMT AF FUGLEN for (CCSprite cloudSprite in targetsToDelete) targets removeObject cloudSprite self removeChild cloudSprite cleanup YES N R SOLEN BLIVER RAMT AF FUGLEN for (CCSprite solSprite in targetsToDelete) targets removeObject solSprite self removeChild solSprite cleanup YES if (targetsToDelete.count gt 0) projectilesToDelete addObject bird targetsToDelete release N R FUGLEN BLIVER RAMT AF ALT ANDET for (CCSprite bird in projectilesToDelete) projectiles removeObject bird self removeChild bird cleanup YES projectilesToDelete release |
18 | Should your world map have it's own collision object? I am attempting to understand collision detection at the moment. I have seen many examples of a simple flat plane with boxes or cubes which move around on the plane and react when the touch each other (or stop at the plane when dropped). What I am not finding though are more advanced examples where instead of just a flat plane, your map is made up of hills, buildings, walls, etc. Since all of the examples I have found this far use simple primitive collision object types (boxes and spheres), I am curious what the best approach would be for creating a collision object for something like a game map (like dust2 in counter strike). After reading through the bullet documentation I found that you can create a collision object from a triangle mesh, which leads me to believe this might be the best approach. However if your map consists of complex geometry (say hundreds of thousands of verticies and faces), would this be too detailed to use as a collision mesh? Would it then be better to create a separate collision version of the map which is made of simple low poly shapes? My gut is saying "go with the separate low poly version", but if there is no reason for the extra work, it would make more sense to just use the high poly mesh. |
18 | Non rectangular collision detection in Python and Pygame I am programming a ray tracer in python, and I have gotten as far as making a character that can move across a 2d plane and change direction of movement when needed. The problem is this I want to be able to use an image with transparency as the maze that the player travels through, and use transparent parts as parts that aren't walls, where as every thing else is a wall. The way I am using collision detection is by using the quot pygame.sprite.spritecollide quot method, which takes in a Sprite, and a Sprite Group. So I first add the map sprite object to the group, and then in the main while loop, it checks for collision. Here is a small snippet of what that might look like map Map( quot map1.png quot ) quot Map quot class is regular sprite class but with quot image quot and quot rect quot group pygame.sprite.Group() group.add(map) inbetween stuff would be here while loop running True while running event handling stuff would be here if pygame.sprite.spritecollide(player, group, False) print True screen drawing routines would be here As I mentioned, the image has transparency. But never the less, the image rect sticks to the non transparency position that it was, so i have to move the player off screen to get the console to stop saying quot True quot . So what I ask, is there a way that I can check for sprite collision but with transparency? |
18 | Navigate multiple Units on a grid through a tight space with different directions I just started learning about pathfinding algorithms. Assume we have this scenario Blue and Green can move only on those tiles. They can also talk to each other. Blue wants to go through the tunnel and green wants to go too, however both need to pass each other somehow. In case of a "basic" A pathfinding algorithm they will both get stuck in the tunnel. To prevent this issue i had some Ideas Blue can tell green that he should move back first (give blue priority) when they both step next to each other (problems arise when there are more than 2) A better algorithm, that calculates this like an automatic traffic regulator (one will wait till the other frees the path) seems complicated Now I am wondering if there are more efficient methods, how its done in general, if you have better ideas, if you can point me to some algorithms or some papers that adress this issue. |
18 | AS3 hittest with a tweening movieclip, what is the best way? I'm making a simple game. The character is movable with the arrow keys. The enemies are moving around the screen with a (classic) tween. I want to detect collision between the character and the enemies. At first I thought it was working properly, but it also seems to detect a collision on the starting position from the enemies. So even if the enemies are already moving tweening away from their start position, there's a collision detected between the character and these starting positions. (please ask questions if you don't quite get what I mean) First method addEventListener(Event.ENTER FRAME, checkIfHitTest) function checkIfHitTest(Event) if(player.hitTestObject(enemies)) trace("yes") else trace("no") This didn't work properly because it seems to detect the collition even if the enemy moved away from the starting point. (Probably because the ENTER FRAME but correct me if i'm wrong) My question to you What's causing the detection and what is the best way to detect collision between a tweening movieclip and a movieclip wich is movable with the arrowkeys? |
18 | Lerping character moving up and down slope tiles So, when interpolating position against a standard 'horizontal' platform, everything works great. What happens is something like this..... (Question continues after graphic) Now, the question I have is, how do we correctly interpolate the player's sprite (blue circle) against a 45 tile? When I attempt to do this, what happens, is that when the player is going up the slope, it is slightly embedded in the tile and when coming down the slope, it floats slightly above the tile. In the example above, the sprite effectively 'stops' moving along the Y Axis, so therefore, interpolation along that axis stops, however when interpolating the position against a slope, the sprite moves in an X and Y direction, so never stops. I think this is causing the issue, if my logic is correct, some more graphics follow to illustrate what I mean.... What am I doing wrong? How do I interpolate my sprite while making sure it's 'on' the slope at all times? For moving up a slope When moving down slope Summary When interpolating against a horizontal platform, although the sprite isn't rendered on the platform in the frame straight after collision has been resolved, it is rendered on the platform during subsequent frames because the difference between the old and new positions has become 0 as it is no longer moving. However against a slope, again, the initial frame is incorrect but then the sprite moves again, so the next frame is also wrong etc so it never 'settles'. Note it does move at the slope's angle just not on the slope. I'm trying to work out how to get my two points along the 45 slope and interpolate between them (ie, along the slope).... |
18 | Dealing with curved lines in GJK I'm currently using a GJK implementation (supported by EPA for penetration) and I'm trying to optimise the calculation times of distance calculations. One of the biggest hits is trying to solve for distance between a simple 3D shape (ie a cylinder) and a curved line in the shape of a helix (https en.wikipedia.org wiki Helix). I'm just brute forcing them by chopping the helix into a lot of smaller straight lines and solving each one against the 3D shape. Is there a better way to do this? The image below shows the relative shape of the objects and how they can come into contact (the red disk is the moving object). In this screenshot its contacting an end point of the curve, but it will commonly contact anywhere between the end points of the helix. |
18 | Where should I save game object's attributes (hp, score) in Swift? Scenario I have a game with several game objects on screen. Each can have different score and hitpoints. When I use collision detection for cannonball vs. ship (example) I need to know which ship is hit and how much hitpoints it has. Problem I had several approaches from extending SKSpriteNode or SKPhysicsBody but all failed. SKSpriteNode doesn't work, because Swifts collision detection only returns physicsBody and since you can't extend physicsBody, it didn't work to save there ships attributes as well. Question What would be a good approach to save such data to my game objects? I do not need code because I think I can write it myself but I would be happy to read a good suggestion. But if you have already some code written and a good solution for this problem, I would not be angry to read it ) |
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 | Should I use Box2D for collision detection only (not simulating physics)? I'm using Box2D only to check collisions and for no physical simulation. I create bodies (and shapes for them) and use my own code to move them, by setting their velocities and positions every frame. I only fetch collision data from the Box2D world. Is this a good idea? For example, can it cause undefined behaviour from Box2D? Is there a more performance friendly way of dealing with different shape collision detections? Do better methods exist for this? |
18 | Penetration Depth into a Planar Polygon I'm working on a self made physics engine, and I'm wondering about the best way to calculate the penetration depth into a polygon that lies in a plane given that resolution must occur along the polygon's normal. My current system correctly uses GJK EPA to detect if a polygon that lies in a plane is intersecting a 3D collider. However, in a case such as the one illustrated below, EPA would not calculate the separating axis to be along the plane normal, but rather outwards parallel to the plane, as that is the direction of minimum penetration. My first thought was to simply manually alter the resolution direction. After GJK detects a collision, I can calculate the support mapping of the polygon in the opposite direction of the plane's normal, then take its perpendicular distance from the plane as its penetration depth. However, in a case such as the one below, this would yield an incorrect penetration depth, as the support point does not project onto the plane. What's the best way to go about getting the penetration depth into the polygon, but only considering penetration of points on the polygon that actually project onto the polygon? |
18 | How to get the overlap volume of OBB and or ABB? The following code is a current attempt at a function I have to determine if two bounding boxes overlap. The bounding box structures are min x,y,z , max x,y,z The following .gif shows the current undesired behavior. aabbOverlap(otherWorldAABB) copied from http blog.meltinglogic.com 2015 04 aabb overlapping area Vector3 min Vector3(max(min1.x, min2.x), max(min1.y, min2.y), max(min1.z, min2.z)) Vector3 max Vector3(min(max1.x, max2.x), min(max1.y, max2.y), min(max1.z, max2.z)) return Math.max(this.worldAABB 0 0 , otherWorldAABB 0 0 ), Math.max(this.worldAABB 0 1 , otherWorldAABB 0 1 ), Math.max(this.worldAABB 0 2 , otherWorldAABB 0 2 ), , Math.min(this.worldAABB 1 0 , otherWorldAABB 1 0 ), Math.min(this.worldAABB 1 1 , otherWorldAABB 1 1 ), Math.min(this.worldAABB 1 2 , otherWorldAABB 1 2 ), The gif has a render of the two entities bounding boxes the house and robot they are rendered in pink and then green when they overlap. Then I try to render the verts and the volume for the overlap section in White. You can see in the gif that some of the verts are way off from what you would expect and the volume gets skewed Why I need this I am using the AABB collision as the broad phase of my detection test. I want to calculate the overlap to restrict the narrow phase algorithim to within that overlap space. The narrow phase pass i'm using is a swept sphere to triangle detection. I want to limit the mount of triangles scanned to within the overlap. |
18 | Wall collision and sweep and prune algorithm I am documenting myself on collision detection algorithms. If I understand well, "sweep and prune" algorithm using frame coherence is powerful to detect object vs object collisions (almost as 0(n)). I am wondering if this algo is good for object vs wall collision ? Suppose you have a big plane wall that is tilted regarding the axes of the "sweep and prune" algorithm (in a 3D game), because it is tilted the bounding box is quite big, and the wall bounding box will be detected as colliding a lot of objects. Similarly if a room is tilted regarding the axes of the algo (and the room is not a cube, but a complex geometry), then all walls collides almost all objects in the room, and the "sweep and prune" algo is useless for this problem. A turnaround could be to split the wall in many little faces before the algo ? Or are there other fast specific algos to detect object vs (big)wall collisions ? |
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 get the overlap volume of OBB and or ABB? The following code is a current attempt at a function I have to determine if two bounding boxes overlap. The bounding box structures are min x,y,z , max x,y,z The following .gif shows the current undesired behavior. aabbOverlap(otherWorldAABB) copied from http blog.meltinglogic.com 2015 04 aabb overlapping area Vector3 min Vector3(max(min1.x, min2.x), max(min1.y, min2.y), max(min1.z, min2.z)) Vector3 max Vector3(min(max1.x, max2.x), min(max1.y, max2.y), min(max1.z, max2.z)) return Math.max(this.worldAABB 0 0 , otherWorldAABB 0 0 ), Math.max(this.worldAABB 0 1 , otherWorldAABB 0 1 ), Math.max(this.worldAABB 0 2 , otherWorldAABB 0 2 ), , Math.min(this.worldAABB 1 0 , otherWorldAABB 1 0 ), Math.min(this.worldAABB 1 1 , otherWorldAABB 1 1 ), Math.min(this.worldAABB 1 2 , otherWorldAABB 1 2 ), The gif has a render of the two entities bounding boxes the house and robot they are rendered in pink and then green when they overlap. Then I try to render the verts and the volume for the overlap section in White. You can see in the gif that some of the verts are way off from what you would expect and the volume gets skewed Why I need this I am using the AABB collision as the broad phase of my detection test. I want to calculate the overlap to restrict the narrow phase algorithim to within that overlap space. The narrow phase pass i'm using is a swept sphere to triangle detection. I want to limit the mount of triangles scanned to within the overlap. |
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 | Collision library for bullet hell in Python I am making a bullet hell game in Python and am looking for a suitable collision library, taking the following into consideration The library should do 2D polygon collision. It should be very fast. As a bullet hell game, I expect to do collision checks between hundreds, likely thousands of objects every frame at a consistent 60fps. Good documentation Permissive license (like MIT, not GPL) I am also considering writing my own library in C C and wrapping with python ctypes in the event that no such library exists, though I do not have experience with collision detection algorithms, so I am not sure if this would be more trouble than it's worth. Could someone provide some guidance on this matter? |
18 | Swept 3d capsule intersection with AABB, what am I actually supposed to use to accomplish this? I'm trying to figure out how to do continuous collision with a capsule (which would represent a collision volume for a player for example). Given how common the capsule is in many game engines, and the fact it is merely a circle swept along a line, I would assume that even just normal collision between it any boxes, triangles arbitrary facets would be abundant, however I'm having a hard time finding anything on capsule collision. Some how I guess I could figure out the swept volume object intersection (box 4 capsule collision detection), and binary search my way down to an approximate collision, but this seems far from ideal, especially given the simple shapes involved. I feel given the shapes I should be able to intersect directly and receive the results. I'm not sure how to figure out quot where quot something intersected along a swept series with other methods (like GJK). For my case, I'm currently focused on just AABB collisions and vertically oriented swept 3D capsules, which I hope to resolve (move capsule appropriately back with AABB collision). |
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 | How do I get the axes for SAT collision detection In SAT collision detection how do I calculate the axes for projection? |
18 | How can I do fast Triangle Square vs Triangle collision detection? I have a game world where the objects are in a grid based environment with the following restrictions. All of the triangles are 45 90 45 triangles that are unit length. They can only rotate 90 . The squares are of unit length and can not rotate (not that it matters) I have the Square vs Square detection down and it is very very solid and very fast (max vs min on x and y values) Wondering if there are any tricks I can employ since I have these restrictions on the triangles? |
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 | Why does my RigidBody collision fail depending on which entity is moving? I am working on a UDK project and have a collision problem. I have a Crate which is a kActor with RigidBody physics and my player who is a Pawn. When my player moves and collides with the crate, the event Bump is called, as expected. However, when my Crate collides with the Pawn when the Pawn isn't moving, the Bump event is not called. In this case, the crate goes through my Pawn without any collision. How can I make this collision case work such that it raises the Bump event? |
18 | Dealing with collisions across adjacent static bodies The Problem I have the following setup A, B and C are rectangular static bodies in box2d. p is a circular dynamic body in box2d. The movement of 'p' is solely controlled by the current gravity force of the world. When 'p' collides with a static body (A, B or C) I play a bouncy sound. I handle this through a standard ContactListener. No problems there. The problem arises when 'p' is on 'A' and traveling left towards 'B'. This causes another collision to fire (on 'B') which results in another bouncy sound which is unwanted. If however 'p' was to be traveling right and contacted 'C' I would want the sound to play (given enough velocity, etc). TL DR When sliding across multiple static bodies how do I effectively ignore collisions from a body that is on the same 'line' I'm already on? What I've Tried I've tried numerous different approaches such as on collision tracking that normal as my 'ground' normal and ignoring collisions from the same normal. This works until I do something like make contact with 'C' which then becomes my new 'ground' normal. But having never lost contact with 'A' if I go back towards 'B' I will trigger another collision and we're back to square one. The Plea Looking for code based solutions or ideas if at all possible. I've considered trying something like a chain shape around my level's collidable areas, but with certain parts of my world being dynamic I don't feel like that's an adequate solution. Thanks! |
18 | 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 | 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 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 Collision in Canvas Balls Overlapping When Velocity is High I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls. I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it Check collision between two bodies function collides(b1, b2) Find the distance between their mid points var dx b1.x b2.x, dy b1.y b2.y, dist Math.round(Math.sqrt(dx dx dy dy)) Check if it is a collision if(dist lt (b1.r b2.r)) Calculate the angles var angle Math.atan2(dy, dx), sin Math.sin(angle), cos Math.cos(angle) Calculate the old velocity components var v1x b1.vx cos, v2x b2.vx cos, v1y b1.vy sin, v2y b2.vy sin Calculate the new velocity components var vel1x ((b1.m b2.m) (b1.m b2.m)) v1x (2 b2.m (b1.m b2.m)) v2x, vel2x (2 b1.m (b1.m b2.m)) v1x ((b2.m b1.m) (b2.m b1.m)) v2x, vel1y v1y, vel2y v2y Set the new velocities b1.vx vel1x b2.vx vel2x b1.vy vel1y b2.vy vel2y You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters function Ball() Random Positions this.x 50 Math.random() W this.y 50 Math.random() H Random radii this.r 15 Math.random() 30 this.m this.r Random velocity components this.vx 1 Math.random() 4 this.vy 1 Math.random() 4 Random shade of grey color this.c Math.round(Math.random() 200) this.draw function() ctx.beginPath() ctx.fillStyle "rgb(" this.c ", " this.c ", " this.c ")" ctx.arc(this.x, this.y, this.r, 0, Math.PI 2, false) ctx.fill() ctx.closePath() |
18 | What technique can I use to animate interaction between tiny objects in a sim game? In simulation games like Sim City and Factorio, there are numerous interaction between tiny objects that needs to be animated. e.g. random people walking on the sidewalk, then waits for a bus, then board the bus tiny cars waiting in line for each other at the traffic junction thousands of items on a convey belt and the robotic arm needs to wait for an item to arrive in front of it to pick it up conveyor belt sections transferring items from one to another. I expect the collision detection check for every tiny object independently will eat a lot of CPU what technique can I use in such a game to avoid the heavy computation and make it look like it's realistic? |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.