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".


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


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!!


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)


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.


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


How 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.


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.


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.


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 ?


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 )


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!


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?


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


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.


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?


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?


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.


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?


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?


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.


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)


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


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?


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?


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...


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?


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?


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?


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?


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"


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)


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.


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!


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?


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!


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.


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.


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?


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?


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...).


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


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?


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.


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.


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)?


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.


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?


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).


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


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.


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?


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.


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?


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)....


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.


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 )


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")


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?


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?


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.


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 ?


What data should a generic collision detection system gather? I'm working on a relatively generic 2D AABB collision detection system for a game engine, and I've re written it more times than I'd like to admit, due to not calculating or recording specific details of each collision. Right now, this is what I'm collecting Collision time as a fraction of an update cycle in the game loop. Location of the collision. ID of the colliding object. Each object has a Set that holds this data for each collision (I'm working with a component entity system) so other systems can use the recorded data. The problem I just ran into was that I needed to know which side of the object the collision takes place on. What other values or points of interest should I calculate or record, per collision? What do you look for in a standard collision detection system?


How 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.


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?


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).


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?


How do I get the axes for SAT collision detection In SAT collision detection how do I calculate the axes for projection?


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?


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?


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?


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!


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


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


2D 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()


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?


Predictive Collision Detection Find Time Of Impact I have a green box at a starting position A. It can move along two paths A to B is linear motion A to C is under the influence of gravity (non linear) The thin vertical line is a fixed colliding wall. All objects are represented with axis aligned AABB bounding boxes. For the path A to B, if my understanding is correct, I (think I) can determine the time of impact (T0) on the wall based on swept AABB collision techniques. this case simply reduces to motion along x axis, and time of impact can be calculated easily. My question is for path A to C. Under the influence of gravity how can I determine the time of impact (T1) relative to the starting time T at location A. (The motion of A to C can be predicted using the standard equations of motion) Are there any techniques algorithms available for this? EDIT To clarify the vertical wall is illustrative walls can be arbitrarily vertical or horizontal or both (like a corner). They will be stationary, and axis aligned though.


Unity Particle System collision detection problem I'm using Unity 3.5.5f3 wich has the Shuriken particle system. I've made a blood particle system based on Unity's demos. (Exploding paint Blood ) The blood is flowing and when it collides with a Plane Transform wich I've created a small pool of blood spawns as a Collision Sub Emitter. My main problem is that when I want to add another object to collide it just doesn't want to work. When I create a cube, and set it as a collision plane the collision will only occur at the half of the cube. I want this to happen When it reaches the cube's surface the sub emmiter activates, and when the surface is horizontal it appears horizontally, and if it's vertical then vertically. Now it just appears horizontally everytime like in the picture. How could I solve it?


Collision detection without classes, in Pygame I am writing a game in Pygame and want to get collision detection working. The aim is that when an object hits another, the target object disappears. I want to avoid having classes for now, to keep things simple. This makes it difficult to get collision detection working, because the Rect method in Pygame assumes classes. The logic I want to achieve is if object hits a target object target object disappears What's the minimal code I'd need to achieve this?


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


Finding roots zeros for collision detection? For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the x y Cartesian plane, but am now interested in understanding the basics of a priori collision detection... In the link here, I noticed the reference to Newton s Method. So, I want to better understand the link b w finding zeros of an equation and detecting a posteriori collision. Let's start with the most obvious case of finding roots of an equation If you have a projectile's trajectory modeled as a quadratic function, you can find the roots to predict at what time the height will equal zero (or any other constant height, actually, by just solving f(x) C to be f(x) C 0 and then finding roots of that expression). So, as I understand, finding the root can tell me the time at which the object will be at any chosen height. More broadly, we basically know the (x,y) location of the object for any given time. But how does root finding, in particular, translate to detecting collisions with another object? (The other object may be stationary, or be moving. If the latter, do you also determine roots location of this moving object as well? Calculate the (x,y) trajectory of both objects and determine where they will intersect?) Again, the basic question is where does root finding come into play? Any links to a basic primer on this topic, with a simple example would also be greatly appreciated.


How to implement 2d collision detection that is immune to low framerate and fast movement? I am trying to implement my own collision detection for a 2.5d voxel style platformer using Three.js. I have a problem with my implementation if the framerate is too low or the character is moving too fast (usually when falling from high places) it falls right through. Is there a way to improve collision detection to be immune to problems like this? This is how I detect collisions function render() requestAnimationFrame(render) setVelocity() animate() manageCollisions() renderer.render(scene, camera) function manageCollisions() Check every game object for collision gt TODO implement broad phase when dealing with many objects for(i 0 i lt world.length i ) Check for bottom collision lt ALWAYS check (unless moving up) if(velocityY lt 0) if( (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("bottom collision " i) velocityY 0 jumped false grounded true character.position.y world i .position.y world i .height 2 character.height 2 0.1 0.1 prevents shaking else grounded false Check for right collision lt ONLY if moving right (velocityX is positive) if(velocityX gt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("right collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for left collision lt ONLY if moving left (velocityX is negative) if(velocityX lt 0) if( (character.position.y) lt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2)) console.log("left collision" i) velocityX 0 character.position.x world i .position.x world i .width 2 character.width 2 check for top collision lt ONLY if moving up (velocityY is positive) if(velocityY gt 0) if( (character.position.y character.height 2) gt (world i .position.y world i .height 2) amp amp (character.position.y character.height 2) lt (world i .position.y world i .height 2) amp amp (character.position.x character.width 2) gt (world i .position.x world i .width 2) amp amp (character.position.x character.width 2) lt (world i .position.x world i .width 2)) console.log("top collision" i) velocityY 0 character.position.y world i .position.y world i .height 2 character.height 2


How do I determine the collision normal in an axis aligned bounding box collision? I have a 3d moving box and a stationary box. I can detect collisions ok but now I would like to slide the moving box against the stationary box as a collision response. For this I need the normal of the face that collides with the moving box. Does anyone know how I figure this out? It doesn't seem like the collision test gives me this information. Any help is appreciated.


Tile based collision detection errors if player is smaller than tiles I have implemented a tilemap where each tile is at a non negative x and y position. (So at the moment think like chess) At the moment a tile is 16, 16 pixels in size Tile 0,0 is at the left bottom corner Some tiles should be collidable. I've never implemented something like that and during research stumbled upon https jonathanwhiting.com tutorial collision The general idea collision response handling let mut new pos Point2 new(curr pos.x x offset, curr pos.y) let collision on x collide with world( amp new pos, amp world) if !collision on x transform.translate x(x offset) new pos.y curr pos.y y offset let collision on y collide with world( amp new pos, amp world) if !collision on y transform.translate y(y offset) The collision detection fn collide with world(new pos amp Point2 lt f32 gt , world amp World) gt bool TODO make these sizes i16 instead so we can grow in any direction! let mut left tile u16 (new pos.x TILE SIZE IN PIXELS as f32) as u16 1 so that we do not collide until we are exactly at the thing let mut right tile u16 ((new pos.x PLAYER WIDTH 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut top tile u16 ((new pos.y PLAYER HEIGHT 1.0) TILE SIZE IN PIXELS as f32) as u16 let mut bottom tile u16 (new pos.y TILE SIZE IN PIXELS as f32) as u16 println!("new pos ? , left , right , top , bottom ", (new pos.x, new pos.y), left tile, right tile, top tile, bottom tile) Useless as long as we use unsigned coordinates if left tile lt 0 left tile 0 if right tile gt WORLD WIDTH IN TILES right tile WORLD WIDTH IN TILES Useless as long as we use unsigned coordinates if bottom tile lt 0 bottom tile 0 if top tile gt WORLD HEIGHT IN TILES top tile WORLD HEIGHT IN TILES let mut any collision false for i in left tile.. right tile for j in bottom tile.. top tile let tile world.get tile(i, j) println!("tile at ? is ? ", (i, j), tile) match tile Some(tile) gt if tile WALL println!("hit a wall at ? !", (i, j)) any collision true None gt (), return any collision I basically took (or tried to take) the optimised version of the linked blog entry. Now to the problems If PLAYER WIDTH and PLAYER HEIGHT are both 16.0 collision works fine But note that I had to put 1.0 in the calculation of the right tile and top tile, else the collision for UP and RIGHT would occur one pixel to early (so the player would never touch walls to their top or right) This change alone makes me a bit suspicious looks like I made an error there. The real problems start if the player is smaller than a tile In the following screenshots the following rules apply ) the PLAYER WIDTH and PLAYER HEIGHT are both 8 ) Greenish tiles are the only walls! ) All the screenshots were taken in ONE run no parameters were changed during this run! 1) Trying to collide with right tile overlapping 2) Trying to collide with top tile cannot go any nearer than 4 pixels (half the height of the player) 3) Trying to collide with left tile cannot go any nearer than 4 pixels (half the width of the player) 4) Trying to collide with top tile suddenly overlapping although different tile didn't collide? 5) Trying to collide with bottom tile cannot go any nearer than 4 pixels I cannot grasp 2 and 4 at the moment.