_id
int64
0
49
text
stringlengths
71
4.19k
18
Collision of grenadelauncher shell The shell of a grenadelauncher is very small (10cm) and the speed is very fast (80m s). Collision detection using colliders is impossible. To get the collision point of a rocket launcher I send a Ray out from the rocket with a length of say 5 metres. If the Ray detects an object it will wait for 5 SpeedOfRocket seconds and then detonate. A rocket travels in a straight line, therefore no problem Grenades however travel in an Arch. They are not selfpropelled, they slow down due to air resistance and they are pulled down by gravity. If I fire a grenade up into the air and use a Ray to detect the collision, it will simply fall through the floor, or another object. The grenade doesn't rotate towards the direction of travel. Using a second and third Ray to detect collisions behind and below the grenade catch all collisions successfully. However you will not be able to shoot a grenade closely above a hill or through a narrow window without it triggering a collision if within range of the Ray. For now I have "solved" the problem by using the grenade just like a rocket. I simulate gravity by simply rotating the grenade as it moves. One ray to catch collision is enough because the Grenade will always face the direction of travel. It works fine if you use the Grenade Launcher "normally". Until you shoot it like a mortar launcher straight up in the air. I find it mathematically impossible to simulate the trajectory as such. There are too many variables involved and it would be a ridiculous attempt at solving a (what seems to be) a trivial initial problem. I need to get the grenade to face the direction of travel like this
18
What algorithms exist for generating collision geometry from an image? I am currently working on a game using SFML and Box2D. I am interested in generating collision geometry from the sprite data that I load into SFML. So, for example, an algorithm that would do this would take an image and find the edges (for example where the alpha area starts) and then generating a polygon that fits to those edges. Can I be pointed to any resources that describe an algorithm to do this?
18
Sphere intersection Stuck I have two spheres that are bounded by spheres for collision detection. I do not want them to intersect. My intersection works. But it gets stuck. Once the function returns true, I cannot get it out. I tried collideBool ObjectOne.Intersect(ObjectTwo) if(collide true) leftright leftright updown updown else if(GetAsyncKeyState(VK RIGHT)) leftright dt if(GetAsyncKeyState(VK LEFT)) leftright dt if(GetAsyncKeyState(VK DOWN)) updown dt if(GetAsyncKeyState(VK UP)) updown dt collide false My sphere gets stuck. What is a way around this?
18
Change collision action I have a collision detection and its working fine, the problem is, that whenever my "bird" is hitting a "cloud", the cloud dissapers and i get some points. The same happens for the "sol" which it should, but not with the clouds. How can this be changed ? ive tryed a lot, but can seem to figger it out. Collision Code (void)update (ccTime)dt bird.position ccpAdd(bird.position, skyVelocity) NSMutableArray projectilesToDelete NSMutableArray alloc init for (CCSprite bird in projectiles) bird.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(bird.position.x, bird.position.y, bird boundingBox .size.width, bird boundingBox .size.height) NSMutableArray targetsToDelete NSMutableArray alloc init for (CCSprite cloudSprite in targets) cloudSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(cloudSprite.position.x, cloudSprite.position.y, cloudSprite boundingBox .size.width, cloudSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , cloudSprite boundingBox )) targetsToDelete addObject cloudSprite for (CCSprite solSprite in targets) solSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(solSprite.position.x, solSprite.position.y, solSprite boundingBox .size.width, solSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , solSprite boundingBox )) targetsToDelete addObject solSprite score 50 2 scoreLabel setString NSString stringWithFormat " d", score N R SKYEN BLIVER RAMT AF FUGLEN for (CCSprite cloudSprite in targetsToDelete) targets removeObject cloudSprite self removeChild cloudSprite cleanup YES N R SOLEN BLIVER RAMT AF FUGLEN for (CCSprite solSprite in targetsToDelete) targets removeObject solSprite self removeChild solSprite cleanup YES if (targetsToDelete.count gt 0) projectilesToDelete addObject bird targetsToDelete release N R FUGLEN BLIVER RAMT AF ALT ANDET for (CCSprite bird in projectilesToDelete) projectiles removeObject bird self removeChild bird cleanup YES projectilesToDelete release
18
Assistance with bomb throwing mechanics akin to Zelda 2D Does anyone have a good algorithm for managing the carrying and throwing of bombs? I've attempted to find a tutorial and can't find anything that covers the subject matter. I'm just looking for a very high level algorithm the coding I can handle.
18
Is there a way to rotate an Ellipse in libGDX for collision detection purposes? I'm trying to avoid having multiple overlapping Circles for a UFO shaped sprite. Two Ellipse objects will perfectly cover the shape of my UFO, but I want to tilt rotate the UFO when flying left and right, while still maintaining collision areas that match the locations of the graphics. The Ellipse reference page doesn't have anything listed for rotation options, just wondering if anyone has ever tried to do this before (and succeeded).
18
My "puck" model object falls right through the "table" model in jMonkeyEngine So I am trying to learn jMonkey, I have understood everything so far, and I thought I understood how to make objects solid, so things can't go through each other. When I create my Collision shapes, I turn on the debugger which shows the shapes, and they appear correct. But when I run the code the puck falls right through the table and I have no idea why? I have been trying to learn from http wiki.jmonkeyengine.org doku.php jme3 beginner hello collision. public class Main extends SimpleApplication public static void main(String args) Main app new Main() AppSettings settings new AppSettings(true) settings.setResolution(1024,768) settings.setFrameRate(60) app.setSettings(settings) app.start() private BulletAppState bulletAppState private RigidBodyControl table phy private RigidBodyControl puck phy Override public void simpleInitApp() bulletAppState new BulletAppState() stateManager.attach(bulletAppState) bulletAppState.getPhysicsSpace().enableDebug(assetManager) DirectionalLight sun new DirectionalLight() sun.setDirection(new Vector3f( 0.1f, 0.7f, 1.0f).normalizeLocal()) rootNode.addLight(sun) cam.setLocation(new Vector3f(0.0f, 2.0f, 7.0f)) initTable() initPuck() initPusher1() initPusher2() My hockey table public void initTable() Spatial table (Node)assetManager.loadModel("Models airTable airTable.j3o") table.setLocalTranslation(0.0f, 5.0f, 2.0f) CollisionShape tableShape CollisionShapeFactory.createMeshShape((Node) table) table phy new RigidBodyControl(tableShape,0.0f) table.addControl(table phy) rootNode.attachChild(table) bulletAppState.getPhysicsSpace().add(table phy) My puck public void initPuck() Spatial puck assetManager.loadModel("Models puck puck.j3o") puck.setLocalTranslation(1.0f, 3.0f, 0.0f) CollisionShape puckShape CollisionShapeFactory.createMeshShape((Node) puck) puck phy new RigidBodyControl(puckShape, 0.05f) puck.addControl(puck phy) rootNode.attachChild(puck) bulletAppState.getPhysicsSpace().add(puck phy)
18
Detecting a Collision Between Two Bodies Undergoing Multiple Transformations I have been searching for an answer to this for a really long time and I have not found any definitive answers as of yet. What I am trying to do is determine if and when two bodies collided between the times t0 and t1. Calculating this is much more straight forward if each body is only either translating or rotating (about center or any point), but when adding multiple transformations on top of each other, things become a bit more messy. I made this animation to illustrate the problem. As you can see, at times t0 and t1 there are no collisions, but between there are multiple collisions occurring. One way I thought of for tackling this problem was to reduce the size of the time intervals. So, between t0 and t1 there would be a total of n updates to check for collisions. This works, but the only way I found that I could guarantee no false negatives, i.e. not finding a collision that happened, was to integrate over extremely small time steps. As you can imagine, this is very costly because it resulted in the tens to hundreds of time steps per body per update cycle. I am not saying this idea has no merit (it makes calculating the collision response much easier since I know the exact points of contact), but I would need to find a way to calculate the minimum number of time steps rather than uniformly moving each body forward one unit of distance rotation until they reach the desired position and orientation. So, my question is two parts Is there a better way of determining if and when a collision occurs? If not, is it possible to calculate the minimum number of time steps? P.S. I think the maximum translation per time step can be the shortest distance between any two points in the body. This would not allow it to hop over anything. When it comes to rotation about the center or orbiting a point I do not know how to determine the minimum angle. It probably has to do with the arc length, but what should that maximum distance be? EDIT this is not right. For a triangle, the base would be the shortest distance between two of its points, but the top could pass through something that is less wide than the triangle base.
18
Binding BoundingSpheres to a world matrix in XNA I made a program that loads the locations of items on the scene from a file like this using (StreamReader sr new StreamReader(OpenFileDialog1.FileName)) String line while ((line sr.ReadLine()) ! null) red line.Split(',') model row 0 x row 1 y row 2 z row 3 elements.Add(Convert.ToInt32(model)) data.Add(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z))) sfepheres.Add(new BoundingSphere(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)), 1f)) I also have a list of BoundingSpheres (called spheres) that adds a new bounding sphere for each line from the file. In this program I have one item (a simple box) that moves (it has its world matrix called matrixBox), and other items are static entire time (there is a world matrix that holds those elements called simply world). The problem i that when I move the box, bounding spheres move with it. So how can I bind all BoundingSpheres (except the one corresponding to the box) to the static world matrix so that they stay in their place when the box moves?
18
What is a good algorithm to detect collision between moving spheres? If (for the purpose of collision detection) 3D objects are represented in a game by spheres, what is a good algorithm to detect a collision between spheres? If each object has a position as of the last frame and a new (desired) position, what is a good algorithm that will identify collisions where the spheres didn't intersect in the previous frame, and they may not intersect in the second frame, but they did intersect somewhere in between?
18
How can I set up a Pong style game using the physics system in Unity? I've just been using Unity and chose to learn it by making a Pong game which sounded simple enough as a "hello world" type of game. My goal was to try and encompass enough of the built in engine without needing to write scripts but I ran into a few problems. Here is my setup so far Paddle Game Object Box Collider RigidBody (Set as Kinematic) Ball Game Object Sphere Collider lt RigidBody (not kinematic) Wall Game Object Box or Plane Collider I've set my material on my Ball to 'Bouncy' and I get a pretty good bouncing ball (given a starting force). I've also added the following script to the Paddles void OnCollisionEnter(Collision collision) BallRidigBody.AddForce(rigidbody.velocity) Here are some of my problems Collision I was trying to figure out why my kinematic objects wouldn't collide before stumbling upon the collision matrix. I was wondering what are good approaches to enable kinematic collisions for my setup Forces I'm confused how ApplyForce should be used. Even if I pick ForceMode.Impulse, is that a constant force? I'm a bit stuck on how to get proper bouncing off the walls and paddle. Since I've already applied a starting force, should my wall apply force on an onCollisionEnter method or change the velocity?
18
Predicting trajectory collisions for multiple moving objects For the most simple of 2D games, I have implemented a posteriori collision detection (overlapping rectangles) on the xy Cartesian plane, but am now interested in understanding the basics of a priori collision detection... On Wikipedia's entry on collision detection, I noticed the reference to Newton s Method. So, I want to better understand the link between 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 rearranging 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?
18
Question regarding simplification of world creation and collision (VISUAL BASIC) In my computer programming class we are creating our own top down adventure games in Visual Basic. Currently I have been able to have the player appear on screen and collide with a block on the screen. My question comes from the collision code which is here Public Sub checkCollide() 'If player's top is in range of the block above it... If yPos Form1.block1Y 49 And (xPos gt Form1.block1X And xPos lt Form1.block1X 49 Or xPos 49 lt Form1.block1X 49 And xPos 49 gt Form1.block1X) Then 'Disable upward movement canMoveUp False Else canMoveUp True End If 'If player's left is in range of the block to its left... If xPos Form1.block1X 49 And (yPos gt Form1.block1Y And yPos lt Form1.block1Y 49 Or yPos 49 lt Form1.block1Y 49 And yPos 49 gt Form1.block1Y) Then 'Disable left movement canMoveLeft False Else canMoveLeft True End If 'If the player's underside is in range of the block below it... If yPos 24 Form1.block1Y And (xPos gt Form1.block1X And xPos lt Form1.block1X 49 Or xPos 49 lt Form1.block1X 49 And xPos 49 gt Form1.block1X) Then 'Disable downward movement canMoveDown False Else canMoveDown True End If 'If the player's right is in range of the block to the right of it... If xPos 24 Form1.block1X And (yPos gt Form1.block1Y And yPos lt Form1.block1Y 49 Or yPos 49 lt Form1.block1Y 49 And yPos 49 gt Form1.block1Y) Then canMoveRight False Else canMoveRight True End If End Sub I was wondering if there was a way to create a struct or class of some sort that allowed for a much simpler way to do this. Each block is a picture box. When creating a new block I need to repeat these steps for each one created, resulting in a huge list that is probably unnecessary. Thanks.
18
Unity OnTriggerEnter2D does not get called when using Raycast In a previous post I talked about creating wires (using B zier curve) using LineRenderer. I am using a PolygonCollider2D to wrap the wire (see below) GameObject wire new GameObject () LineRenderer lineRenderer wire.AddComponent lt LineRenderer gt () PolygonCollider2D wireCollider wire.AddComponent lt PolygonCollider2D gt () After drawing the curve and attaching the collider (as described in previous post), I added a new component to my gameObject (a WireController) WireController wireController wire.AddComponent lt WireController gt () The WireController currently has only one method void OnTriggerEnter2D(Collider2D other) Debug.Log ("I'm hit!") I use a Physics2D.Raycast to check if my mouse pointer is at any point interacting with the wire void CastRay() Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit2D hit Physics2D.Raycast (ray.origin, ray.direction, 100) if (hit) Debug.Log (hit.collider.gameObject.name) If I call CastRay() inside a Update() loop, if (hit) returns true (if the mouse pointer is over the gameObject, in this case, the wire), but the OnTriggerEnter2D method never gets called. A few observations collider.isTrigger true The WireController is attached to the newly created gameObject (it's visible in the Unity editor at runtime) Any help is much appreciated!
18
Libgdx collision detection and response I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the Rectangle.overlaps method. In response I am trying to find out at what edge the player hits the tile and then react accordingly. Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile). I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since Rectangle.overlaps() is used I am only reacting to a collision already happening. Here the source private void resolveCollision() setUpPlayerRec(allObjects.get(0)) for (Rectangle r2 tiles) if (!playerRec.overlaps(r2)) continue else onCollisionWithTile(r2) private void onCollisionWithTile(Rectangle r2) Gdx.app.log("Collision Detected", "Player collided with tile") float diff if (playerRec.x playerRec.width lt r2.x) LEFT EDGE OF TILE controlledPlayer.getPosition().x (r2.x playerRec.width) controlledPlayer.getVelocity().x 0 else if (playerRec.x gt r2.x r2.width) RIGHT EDGE OF TILE controlledPlayer.getPosition().x (r2.x r2.width) controlledPlayer.getVelocity().x 0 if (playerRec.y lt r2.y) HIT TOP OF TILE diff (playerRec.y playerRec.height) r2.y controlledPlayer.getPosition().y Math.abs(diff) jumptime MAXJUMP controlledPlayer.setJumpState(JUMP STATE.GROUNDED) else if (playerRec.y lt r2.y r2.height) HIT BOTTOM OF TILE controlledPlayer.setJumpState(JUMP STATE.GROUNDED) jumptime 0 diff playerRec.y (r2.y r2.height) controlledPlayer.getPosition().y r2.y r2.height
18
How to resolve collision when both of the intersecting bodies were moving? Suppose there are two quadrilaterals A and B. A is stationary but B is moving. They collided. Now B is inside A. To check if they are intersecting I can use 2d separating axis theorem (SAT). To push B out of A so that they are not intersecting anymore, I can again use SAT to get the Minimum Translation Vector(MTV) and project B out of A using it. My problem is, what should I do when both A and B were moving, and then they collided? I can't project A out of B or B out of A alone since both of them were moving. How should I separate them?
18
Trying to create a sphere in UDK on which I can stand Trying to build a globe in UDK, but when I do (create a sphere), my player falls straight through it. How do I make a sphere that I can walk on? Every other shape (cube, cone...etc) work just fine. Edit Specifically, I want to build a CSG Brush sphere, not a mesh sphere. It appears to work just fine if I set the "sphere exptrapolation" to 1 or 2, but if I bump it up to 3 or higher, I fall right through. I literally created 2 spheres next to each other, one set at "2" and one at "3" I can walk from the top of the "2" sphere and jump onto the "3" sphere, but I fall right through it.
18
Issue with 2d Angular Car Collision Response I am having trouble getting the angular collision response to work properly in my 2d car simulation. I have gotten the linear collision response to work between the vehicles, however, the angular collision response does not seem to be working. The problem seems to arise from my slip angle calculation for the car, and it seems to override the angular impulse. The slip angle is necessary to make the vehicle move realistically. Here's the code to calculate the slip angle Calculate slip angle for front back wheel this.wheels.front.slipAngle Math.atan2(this.localVelocity.y yawSpeedFront, Math.abs(this.localVelocity.x)) this.wheels.back.slipAngle Math.atan2(this.localVelocity.y yawSpeedRear, Math.abs(this.localVelocity.x)) As can be seen in the following pictures, the car rotation response is correctly simulated when it hits the top of the car and rotates clockwise. On the other hand, when the car hits the bottom of the other car, the rotation should be clockwise, but actually still goes clockwise. It seems to me that the problem arises because the slipAngle overrides the angular rotation of the collision. My project can be seen here https victorwei.com projects car sim Feel free to take play around with the simulation and view the code to figure out the issue. If there are any suggestions on how to mitigate this problem, that would be greatly appreciated.
18
Complex Models using bounding boxes in xna 4 I'm new to XNA, and have just started looking into collision detection. I've managed to get a bounding sphere around my first person camera object and i want to check the collision between that and the walls of my cube. e.g. this is a cube i have built in Maya and it is 1 combined mesh. What i want to do i check my bounding sphere against the inside of the walls. and also allow the myself to enter in and out of the holes in the sides and th top. My first thought would be using each vertex to test against collision but i have no idea how to do this, since this is the first time attempting. Can anyone point me in the right direction?
18
Collision quadrant in godot appears I am learning to use godot following this video Collisions with Autotiles The problem is that when I create the collision for the cliffs using tilemap, it appears me a blue quadrant indicating the collision. What should I do for what these quot quadrants quot do not appear? As you can see, all the cliffs are blue for indicate me the collision, but I have no idea about what to do for hide them.
18
Get normal dependent on collisions position As I hask ask here I'm working on how my objects can move over the terrain and other objects. My proposal and also an idea in the answers was to calculate the rotation from the object with the normals from other objects around (under and in front) the moving object. My main problem for that is how I can get the normal from an object at a special position. Let's take the ramp on the road from the old example. It depends from which side my car comes. If it comes from front it can drive along the ramp but if it comes from back it moves against the wall. Of course there are other normals if I come from the other side. All my objects have these variables float vertices float normals short drawOrder float modelMatrix AABBox boundingBox So you see I can allways get the vertices, normals and the position. I can also test if the object collides with another object with the bounding box (axis aligned) but I have no idea how I can get the normal where the collision happens but that is the important thing for the rotation of the car. Do you have any ideas or are there usual way how to do this?
18
Pygame collision detection less frequent when objects are increased I currently experiencing an issue in pygame where whenever i increase the number of objects e.g. platforms, rocks for a in range(150) rock Rock(0,0) OR incresing the range which they spawn in rock.rect.x random.randrange( 200,30000) rock.rect.y random.randrange(80,500) rock list.add(rock) all sprites list.add(rock) LINE 232 (which i really need to do for an ENDLESS mode) collision detection between the player and all the objects that have have been changed will become less frequent, so the character will just go through th objects as they weren't even there... you can see the character fall through the objects, it falls through in front of the object and not behind. All game code is below, I have tried a number of different techniques and values but I have found that these numbers and ranges work best. Collision Detection code FOR PLATFORM medium collide pygame.sprite.spritecollide(player, medium list, False) if medium collide player.rect.y 2 FOR ROCK rock collide pygame.sprite.spritecollide(player, rock list, True) if rock collide lives 1 if rock collide player.rect.y 100 player.rect.x 50 !!!!!GAME CODE BELOW!!!!! GAME CODE
18
Creating the game space for a 2D game How does one setup the game space for a game so that obstacles can be spawned? Examples would be ice climber or the iphone doodle jump. Tile maps are limited in size and would need to change often if the user jumps a lot. How would this be done in another way than tile maps. How or what is used to create the notion of a game world where these spawned ledges obstacles are placed as the user progresses through the stage? What is actually moving if the user jumps from ledge to ledge, what are the ledges based on in terms of the game world space. What data structure or representation could the game use to reference and manage the spawning of these obstacles ledges? How is a continuous environment created which creates collision objects as the user progresses?
18
How to program destructibles? I'm thinking about programming a 2d simulation of a spaceship that takes damage depending on where the projectile came from (e.g. from behind engine, from the front lasers, sides hull, etc.). When a given part is below a certain durability factor it explodes into physics simulated particles. What is a good way of storing such particles (ship built out of parts, parts built out of particles, e.g. 6px triangles) taking into consideration the following different parts have different shapes, it might be needed to add more parts in the future, possibility of avoiding a pixel perfect projectile to part collision detection, the spaceship should be affected by physics but particles shouldn't unless exploding.
18
Calculating contact points with SAT After detecting a collision between two convex shapes by using separating axis theorem and calculating MTV. How can I calculate the contact points?(for applying torque to the rigid body).
18
Ray box intersection problem I try to implement ray box intersection algorithm given by the following code. However, I'm not really understand for two cases as shown in the following figures. Firstly, when the box is located in front of the ray, why the code give intersection even though the end point of the ray doesn't intersect with the box. A similar observation can be seen from the second case when the ray origin is located inside the box. Is this nature of the algorithm? How can solve this problem? r.dir is unit direction vector of ray dirfrac.x 1.0f r.dir.x dirfrac.y 1.0f r.dir.y lb is the corner of AABB with minimal coordinates left bottom, rt is maximal corner r.org is origin of ray float t1 (lb.x r.org.x) dirfrac.x float t2 (rt.x r.org.x) dirfrac.x float t3 (lb.y r.org.y) dirfrac.y float t4 (rt.y r.org.y) dirfrac.y float tmin max(max(min(t1, t2), min(t3, t4))) float tmax min(min(max(t1, t2), max(t3, t4))) if tmax lt 0, ray (line) is intersecting AABB, but the whole AABB is behind us if (tmax lt 0) t tmax return false if tmin gt tmax, ray doesn't intersect AABB if (tmin gt tmax) t tmax return false if tmin lt 0 then the ray origin is inside of the AABB and tmin is behind the start of the ray so tmax is the first intersection if(tmin lt 0) t tmax else t tmin return true
18
How do I implement collision detection with a sprite walking up a rocky terrain hill? I'm working in SDL and have bounding rectangles for collisions set up for each frame of the sprite's animation. However, I recently stumbled upon the issue of putting together collisions for characters walking up and down hills slopes with irregularly curved or rocky terrain what's a good way to do collisions for that type of situation? Per pixel? Loading up the points of the incline and doing player line collision checking? Should I use bounding rectangles in general or circle collision detection?
18
How can I optimise collision checks for a large number of AI units? Let's say I got 100 Orcs in my 3D world and they all aim to kill each other. That means for every 1 Orc I have to check for collision with the 99 others. That will give me 99 2 which is about 10,000! That many collision checks every update (24 60 times a second) only for the AI will probably use my whole GPU CPU. How can I handle such a large number of AI? How is this is done in games with large numbers of NPCs (e.g. Skyrim, Fallout, Red Dead Dedemption...).
18
Determine the bullet particle reflection off of a circle in node js using SAT lib functions I can see how the calculation should occur from other examples such as How to bounce a 2d point particle off of a circular edge. But I could use some help with the specifics for my inputs given during a game loop that is progressing moving the bullet each game loop tick, and then detecting and handling collisions. I've tried to mock up an example nodejs script using the SAT lib http requirebin.com ?gist 4a5c208dc39d3c3be262abb05fa791a3 .. with the console logs tracing a few variables, including the output target vector. My question essentially lies in understanding how I can use the SAT vector functions like dot() or reflect() to produce the reflection? https github.com jriecken sat js classes Even pseudo code would help me understand what exactly the operation needed to determine the reflection point (not just the angle, but the bullets new target vector) given my inputs of a bullet x,y position colliding with and a circular wall.
18
Game Physics Calculating a collision response using the Separating Axis Theorem? I am working on a project in which I have implemented the Separating Axis Theorem to detect collisions between objects. My current collision response is an object that contains whether it is overlapping and what the minimum translation vector (MTV) is. I then take the MTV and add it to the linear velocity of the object we're testing. This all works fine. However, I want to add rotational forces to the object based on the collision. For this, I imagine we will need two things The Minimum Translation Vector, which represents the force A contact point, which is the point at which the MTV force gets applied to the object However, I have been struggling with calculating the contact point for the past two three days. I haven't been able to find good resources on this, unfortunately. How would I go about calculating a suitable collision response as I described? Thank you very much!
18
Color Based Collision Javascript (Cocos2d js) I'm looking to make an isometric game so my partner designed the isometric map (jpg image) along with the map objects (png) on Adobe Illustrator. The thing is I would like to set the player path based on color, for example if the terrain is white the player can go through, if it's black then the player is not allowed to pass. Is this a viable method to do this or are there better methods? Also I'm using Cocos2D js so my coding is JavaScript I would appreciate any suggestions.
18
Acute corner Collision Detection So I have set up a Swept test for AABB vs Line Collision that works fine, now the problem is that I have to deal with acute corners, where this happens As you can see the AABB just falls through the bottom Line, when it should stop. I have been trying to do this for a month now, and I can't find any solution at all. Why does this happen and how do I fix it? Project http murplyx.net sss Move with WAD and draw lines with mouse Source Code http murplyx.net sss js main.js and http murplyx.net sss js vec.js
18
How to integrate Tiled maps and collision detection with pygame? I have been using pygame to make a simple rpg pokemon style game. To create maps I have used the Tiled map editor and then loading them into pygame using pytmx. I have heard that you can add object layers in Tiled to your map, and then use this information for collision detection within your game engine (in this case pygame). Unfortunately, while I know how to load the tmx file into my pygame game, I have no idea how to use the object layers for collision detection. Can anyone provide a minimal example on how to do this? The documentation that I have come across for Tiled appears to be quite minimal and still an active work in progress. As a result I have not been able to find information on using Tiled and object layers for collision detection in pygame.
18
Canvas Paint Mechanic I'm currently working on an idea for a Unity game app with a canvas mechanic. I understand I may have to use particles for the brush paint f x however I can not think of a way to add collision detection let alone the paint itself...onto a canvas... Any suggestions are much appreciated!
18
How to create polygonal or elliptical colliders by python tkinter? I am developing a primitive game by python tkinter (I use canvas). It's not a big project. It's only my own self challenge to create a game using only tkinter and standard python libraries. My problem is colliders. I need to detect collisions of game objects. First I used a circle collider (it's easy). But using only circles in a game is not good, so I decided to use polygonal or elliptical colliders, but I don't know how to do it without external libraries such as pygame. Could anyone help me? My question shorter How to detect polygons' or ellipses' collisions in python tkinter canvas using only standard libraries? P.S. And how to detect collisions of an inclined rectangle?
18
How to perform simple collision detection? Imagine two squares sitting side by side, both level with the ground like so A simple way to detect if one is hitting the other is to compare the location of each side. They are touching if all of the following are false The right square's left side is to the right of the left square's right side. The right square's right side is to the left of the left square's left side. The right square's bottom side is above the left square's top side. The right square's top side is below the left square's bottom side. If any of those are true, the squares are not touching. But consider a case like this, where one square is at a 45 degree angle Is there an equally simple way to determine if those squares are touching?
18
How to handle collisions without ugly conditionals and type checking? (I asked a similar question, but this one is far more specific). How can I handle collisions without having to do a lot of type checking and if statements? People here suggested that when spotting a collision, the collision detector should notify both entities in the collision, and the entities themselves will encapsulate the logic to react to the collision. I like the idea of having the entities themselves decide how to handle the collisions. However I'm not sure how to avoid doing a lot of type checking and if statements inside the handleCollision methods. For example (in psuedocode) class CollisionDetector foreach entity in entities foreach otherEntity in entities if(collision(entity,otherEntity)) entity.handleCollision(otherEntity) class Entity .. stuff omitted void abstract handleCollision() class Alien extends Entity .. stuff omitted void handleCollision(Entity entity) lots of ugly conditionals and type checking if(entity instanceof Missile) die() if(entity instanceof Alien) lifePoints ((Alien)entity).getDamagePoints() if(entity instanceof Wall) setVelocity(0,0) .. etc In OOP we should try to avoid type checking and employ Polymorphism. But I don't see how this can be done in this case. Is there a way to avoid the ugly type checking and lots of conditionals? Or should I just make my peace with it? How is this most commonly done?
18
Sprite Kit keeping character level with the terrain 2d endless runner I've been trying to figure this out exhaustively for the past few days and still haven't found an answer. I have an endless runner built using swift where the character is fixed and the terrain moves to the left. I have edge physics bodies on the terrain, and edge physics bodies that go up and down slopes. The problem is, if I want my character to collide with the ground without being pushed back by it, since the only thing that can make contact with an edge is a dynamic volume. My goal is to keep the character level with the terrain, (assuming they're not jumping). Even on slopes. I've tried ray casting using enumeratebodiesalongraystart, but can't seem to figure out how to get coordinates of where it intersects with the ground. I've tried having an edge body that is vertical, that intersects with the ground(two edge bodies cannot make contact in sprite kit). I've tried dynamic volumes. I've tried Static volumes. Nothing works. I'm not posting code here since I'm really just looking for a general answer to sort of point me in the right direction, but I'm coding in swift. Thanks in advance. Also I have the character in a different bitmaskcatagory than the terrain catagory and they are set up to recognize each other, and do if one of them is a dynamic volume physics body.
18
SAT How to find Shortest line between two static convex 2D Polygons? RI have a pretty standard SAT algorithm that seems to successfully be detecting collisions but now I am looking for some assistance in finding the shortest line between 2 separated Polygons. I have spent quite a bit of time searching and trying things with no success. If someone could point me in the correct direction or give a solution to this I would be most greatful. While a general n polygon vs n polygon solution would be awesome my use case only requires OBB vs OBB. This could simplify the answer.
18
Problem with collisions detection on canvas platformer Having a lot of trouble with my collision detection in my platformer. If you go straight to the right the block will float. Also the corners let the block sink right through and the walls are sticky. It's a bit of a mess. I know for the floating my gravity is a big issue. If anyone could help me out i'd be so so happy. Heres the collision code const calculatedTileSize 1.0 mapTileSize const nextX guy.x guy.velX const nextY guy.y guy.velY const currentMinX (guy.x calculatedTileSize) 0 const currentMaxX ((guy.x guy.width) calculatedTileSize) 0 const currentMinY (guy.y calculatedTileSize) 0 const currentMaxY ((guy.y guy.height) calculatedTileSize) 0 const nextMinX (nextX calculatedTileSize) 0 const nextMaxX ((nextX guy.width) calculatedTileSize) 0 const nextMinY (nextY calculatedTileSize) 0 const nextMaxY ((nextY guy.height) calculatedTileSize) 0 X axis collision if (guy.velX ! 0.0) for (let i nextMinX i lt nextMaxX i ) for (let j currentMinY j lt currentMaxY j ) if (map j i ) guy.velX 0.0 break Y axis collision if (guy.velY ! 0.0) for (let j nextMinY j lt nextMaxY j ) for (let i currentMinX i lt currentMaxX i ) if (map j i ) guy.velY 0.0 physics.gravity 0 else physics.gravity 0.4 The full game is in this codepen https codepen.io charlie1172 pen OeGdvJ
18
How do I apply collision to a turtle I cannot figure out how to apply collision to a turtle. I am in need of help for collision with pen lines and turtles. I want the two to hit and restart the game but I can't get collision on either. import turtle import pygame wn turtle.Screen() wn.bgcolor("black") Draw border mypen turtle.Turtle() mypen.penup() mypen.pencolor('white') mypen.setposition( 300, 300) mypen.pendown() mypen.pensize(3) for side in range (4) mypen.forward(600) mypen.left(90) mypen.hideturtle() Create player 1 player turtle.Turtle() player.setposition(240,240) player.setheading(180) player.color("red") player.shape("classic") player.speed(0) Create player 2 player2 turtle.Turtle() player2.setposition( 240, 240) player2.color("aqua") player2.shape("triangle") player2.speed(0) Set speed variable speed 3 Define functions def turnleft() player.left(30) def turnright() player.right(30) def increasespeed() global speed speed 3 Set keyboard bindings for p1ayer 1 turtle.listen() turtle.onkey(turnleft,"Left") turtle.onkey(turnright,"Right") Define player 2 functions def turnleft() player2.left(30) def turnright() player2.right(30) def increasespeed() global speed speed 3 Set keyboard bindings for player 2 turtle.listen() turtle.onkey(turnleft,"a") turtle.onkey(turnright,"d") turtle.onkey(increasespeed,"Up") while True player.forward(speed) player2.forward(speed) Bouandary if player.xcor() gt 300 or player.xcor() lt 300 player.right(100) Boundary if player.ycor() gt 300 or player.ycor() lt 300 player.right(100) Bouandary2 if player2.xcor() gt 300 or player2.xcor() lt 300 player2.right(100) Boundary2 if player2.ycor() gt 300 or player2.ycor() lt 300 player2.right(100)
18
Making the ball go faster makes collision detection impossible I have a simple tennis game like Breakout. I have a ball, and a racquet made from a long rectangle. The ball bounces around the walls, and the game terminates when the ball hits the floor. To prevent this, I have a long racquet I can move horizontally that the ball can hit. Each time the ball hits the racquet, the speed of the ball increases. The speed increases by adding to the number of pixels for each increment of the ball. This means that after a while (around 50 hits), the steps of the ball become quite long. The ball moves at 50 px per frame. With long steps, the ball might just jump over the racquet, and not detect collision. To prevent this, I was thinking of incrementing the FPS, instead, and keeping the ball speed fixed. This would probably work, but I don't think changing the FPS is the right solution. How should I go about solving collision detection at higher speeds?
18
multiple contacts for SAT collision detection I have implemented SAT algorithm for obb obb intersection and I am able to generate a contact for this collision type. My problem is that SAT only generate ONE contact and in many situation I need more than one contact. For example, If I have a big cube and above it I have a small cube I need two contact (two contacts in 2D and 4 contacts in 3D) one for each bottom vertex of small cube. My question is how can I generate more than one contacts with SAT? Thanks.
18
How to decide which GameObject should handle the collision? In any collision, there are two GameObjects involved right? What I want to know is, How do I decide which object should contain my OnCollision ? As an example, let's suppose I have a Player object and a Spike object. My first thought is to put a script on the player that contains some code like this OnCollisionEnter(Collision coll) if (coll.gameObject.compareTag("Spike")) Destroy(gameObject) Of course, the exact same functionality can be achieved by instead having a script on the Spike object that contains code like this OnCollisionEnter(Collision coll) if (coll.gameObject.compareTag("Player")) Destroy(coll.gameObject) Whilst both are valid, it made more sense to me to have the script on the Player because, in this case, when the collision happens, an action is being performed on the Player. However, what's making me doubt this is that in future you may want to add more objects that will kill the Player on collision, such as an Enemy, Lava, Laser Beam, etc. These objects will likely have different tags. So then the script on the Player would become OnCollisionEnter(Collision coll) GameObject other coll.gameObject if (other.compareTag("Spike") other.compareTag("Lava") other.compareTag("Enemy")) Destroy(gameObject) Whereas, in the case where the script was on the Spike, all you would have to do is add that same script to all the other objects that can kill the Player and name the script something like KillPlayerOnContact. Also, if you have a a collision between the Player and an Enemy, then you likely want to perform an action on both. So in that case, which object should handle the collision? Or should both handle the collision and perform different actions? I have never built a game of any reasonable size before and I'm wondering if the code can become messy and difficult to maintain as it grows if you get this sort of thing wrong in the beginning. Or maybe all ways are valid and it doesn't really matter? Any insight is much appreciated! Thank you for your time )
18
3d complex collision and trigger detection I'm a Unity developer and I use monobehavior functions to dot things like collision detection. I have read about articles about collision detection. Most of them work with geometrical structures like sphere or boxes. How are complex collisions with no formal and geometrical structures calculated?
18
How do I calculate distance between a point and an axis aligned rectangle? I have a 2D rectangle with x, y position, height and width, and a randomly positioned point nearby. Is there a way to check if this point might collide with the rectangle if it is closer than a certain distance? Imagine an invisible radius outside of that point colliding with said rectangle. I have problems with this simply because it is not a square!
18
Should particles check if they are in a region, or regions if particles are in them? I have around 100 to 200 particles in my game. Then I have 5 to 20 regions (circle shape) which should count the particles which enter them and add some force to them, so they change their direction. My idea was now to keep a list of all particles and every region should check the whole list every frame, whether a particle is inside it. For this I calculate the distance between the particle and the central point of the region and check weather its lt the radius of the region. Is this the most efficient way to do it? Or should every particle have a list of all regions and check whether they are in one of it? Or a totally different approach? I would like this application to be able to run also on older mobile devices like an iPhone 4S.
18
2D narrow phase line intersection with square bounding box for calculating height efficiently I've performed partitioning of my level into broad and narrow phase. I'm down to narrow phase and focusing on the height from the ground. I want to see what polygon the player is on top of. Since some polygon sectors may be lower than others (this is a birds eye view), I want the player to be stand on top of the highest one. Therefore I thought what I can do is each game tick would be to check which boxes the player intersects, and then find the polygon with the highest 'height' and use that as the base height for the player. An example would be below Is this a viable way of doing it? That this game is 3D, but I only have to do two dimensional calculations for the height which reduces the computation and makes this easier. The level has been cut up into a BSP tree so the following is a gross misrepresentation of the level, however I don't see any obvious way (immediately) to exploit the BST property to find out the highest sector that the player would be standing in. So far the best way I could think of was to use narrow phase collision detection described above and hope that is extremely fast. I am looking for speed here, so if you know of any better algorithms or some faster way of doing this, please let me know. EDIT The focus of this post is for high level algorithms, of which they can be optimized later on. No actual collision detection code has been made yet.
18
Detecting collisions between entities in a text mode game What I'm trying to do is create a terminal soccer game. Without using any modules packages like pygame or anything required to have something not outside of the terminal. So, I did research on a simple code that was supposedly going to work. It required python as expected. Here's the code found on a website. Draw all sprites for entity in all sprites screen.blit(entity.surf, entity.rect) Check if any enemies have collided with the player if pygame.sprite.spritecollideany(player, enemies) If so, then remove the player and stop the loop player.kill() running False How could I turn this into something that works in the terminal?
18
Oriented Bounding Box How to? I've been trying to write my own collision code, less because I want to, more because I want to understand its working. To do this, i've been working off of the popular collision book i'm sure you've all heard of Morgan Kaufmann Real Time Collision. I'm on the subject of Oriented Bounding Boxes. These are boxes that can have an orientaiton applied to them. If it matters, i'm doing my code in 2D. It seems easy enough to just cut out an axis from the books calculations. Here is the OBB they define Region R x x c r u 0 s u 1 t u 2 , r lt e 0 , s lt e 1 , t lt e 2 struct OBB Point c OBB Center Point Vector u 3 Local x , y , and z axes Vector e Positive halfwidth extents of OBB along each axis The confusing one is the Vector array, u. Point c is the center 3 axis position of the box. Vector e is the width, height, and length of the box. Vector u 3 baffles me. My best guess is that it is the center point of each of the 3 sides (with the reflected 3 finishing the box) How does rotation work into this? Is the Vector u 3 taking the roation in somehow? How?
18
Can you help me resolve a bug in mesh collision code? I have entities which walk along a 3D mesh. I move the units along their x,z axis, and every frame I update their y position according to the quad or triangle they are standing on, using Barycentric coordinates. They do walk along the mesh, however every time they enter a new quad or triangle, they quot bob quot up and down on the y axis. Height testing is done by finding the quot bottom left quot vertex of a quot sqaure quot of four vertices made by converting the unit's x,z position into a 1d index into an array of vertices. They move smoothly until they enter a new part of the mesh, where it looks like their y coordinate shifts once very noticeably and then keep moving smoothly. It happens both when testing against the square made by the four vertices around the unit, and with testing against triangles of mesh. Here is the code to find y coordinate on a square float px batchTranslation i .Value.x float pz batchTranslation i .Value.z int index ( int ) ( ( math.floor( pz MAP SCALE ) ) MAP SIZE ( math.floor( px MAP SCALE ) ) ) int bL index int bR index 1 int tL index MAP SIZE float3 p1 vertices bL float3 p2 vertices bR float3 p3 vertices tL float3 normal math.cross( ( p2 p1 ) , ( p3 p1 ) ) float py ( normal.x ( p1.x px ) normal.z ( p1.z pz ) normal.y p1.y ) normal.y HALF HEIGHT batchTranslation i new Translation Value new float3( px , py , pz ) Here is the code for finding the y coordinate on the triangles of the mesh float px batchTranslation i .Value.x float pz batchTranslation i .Value.z int index ( int ) ( ( math.floor( pz MAP SCALE ) ) MAP SIZE ( math.floor( px MAP SCALE ) ) ) int bL index int bR index 1 int tL index MAP SIZE int tR index MAP SIZE 1 float3 V1 vertices bL float3 V2 vertices bR float3 V3 vertices tL float3 V4 vertices tR float py batchTranslation i .Value.y if ( IsInside( V1.x , V1.z , V2.x , V2.z , V3.x , V3.z , px , pz ) ) py CalcY( V1 , V2 , V3 , px , pz ) else if ( IsInside( V1.x , V1.z , V2.x , V2.z , V4.x , V4.z , px , pz ) ) py CalcY( V1 , V2 , V4 , px , pz ) batchTranslation i new Translation Value new float3( px , py , pz ) private float Area( float x1 , float z1 , float x2 , float z2 , float x3 , float z3 ) return math.abs( ( x1 ( z2 z3 ) x2 ( z3 z1 ) x3 ( z1 z2 ) ) 2.0f ) private bool IsInside( float x1 , float y1 , float x2 , float y2 , float x3 , float y3 , float x , float y ) float A Area( x1 , y1 , x2 , y2 , x3 , y3 ) Calculate area of triangle ABC float A1 Area( x , y , x2 , y2 , x3 , y3 ) Calculate area of triangle PBC float A2 Area( x1 , y1 , x , y , x3 , y3 ) Calculate area of triangle PAC float A3 Area( x1 , y1 , x2 , y2 , x , y ) Calculate area of triangle PAB return ( A A1 A2 A3 ) Check if sum of A1, A2 and A3 is same as A Returns y coordinate of point on triangle given point x and z coordinates private float CalcY( float3 p1 , float3 p2 , float3 p3 , float x , float z ) determinant float det ( p2.z p3.z ) ( p1.x p3.x ) ( p3.x p2.x ) ( p1.z p3.z ) float l1 ( ( p2.z p3.z ) ( x p3.x ) ( p3.x p2.x ) ( z p3.z ) ) det float l2 ( ( p3.z p1.z ) ( x p3.x ) ( p1.x p3.x ) ( z p3.z ) ) det float l3 1.0f l1 l2 return l1 p1.y l2 p2.y l3 p3.y
18
Seeking Advice Collision with JBox2d for Top Down or Isometric Maps I Hope I can make this as clear as possible! Currently working on an action RPG game, very early stages, more just the basic ideas down and written in. So i'll start on with my setup Using Java with LibGDX Map creation is done with TILEd Style of map Isometric Collision Engine? ... well this is where I need a bit of guidance and advice. LibGdx is linked in with Box2d which makes it . I'd personally love to use Box2D, more because I've played around with it on a platform level and I liked how it operated with force and impulses etc, however, it seems to be created for only platform style games. So I guess one questions is Can Box2d's properties be easily changed to support a Top Down collision system or an Isometric collision system? I have tried to implement Box2d into a top down game before by setting the gravity to zero, but with no gravity, the other entities on the map just float. (You bump into them and they just start... floating!) What I was originally thinking was once I have my map created in TILEd, I would start adding a collision layer (Or modify the tiles individually) to mark what is passable and what is not. I have seen examples for box2d (again Platform only however) ways to create an Object in TILEd to mark the collidable wall or floor and when loaded it would create the shapes. Box2d would be perfect if it wasn't for the whole floating entity due to zero gravity. So what I am looking for... 1) Is there a way to create Box2D work on a Top Down set up without entities floating? 2) If not, what other solutions do I have for collision? If there is any other information needed for a better response Please let me know! Thank you!
18
Collision detection with curves I'm working on a 2D game in which I would like to do collision detection between a moving circle and some kind of static curves (maybe Bezier curves). Currently my game features only straight lines as the static geometry and I'm doing the collision detection by calculating the distance from the circle to the lines, and projecting the circle out of the line in case the distance is less than the circles radius. How can I do this kind of collision detection in a relative straightforward way? I know for instance that Box2D features collision detection with Bezier curves. I don't need a full featured collision detection mechanism, just something that can do what I've described. UPDATE Thanks a lot for the great answers! I'll have to read up on Bezier curves to fully understand the method you've described. Then I'll get back to you.
18
How do I determine which voxels to test for collision against the player? I've implemented Minkowski subtraction to test whether (and where) two AABBs collide, independent of framerate time step, in my Minecraft like game. But since there may be tens of thousands of voxels, I'm realizing I can't just test everyone of them. Is there an alternative to just scanning for nearby voxels? I worry that if I just do collision for voxels within a fixed range, then I've undone the framerate independence that I had sought.
18
How will the velocities of two moving objects change once they collide? I'm making a small game where things can fly around and collide. Things like boxes and so on. For each object, I have an array of all forces acting upon it, I have it's mass, it's position and it's velocity in both directions (a 2D vector). I know how to detect collision between them, but I just don't know how to react. I used to calculate their orientation towards each other, it they were on top one another, I would just negate their y speed (v.y v.y), and if they were next to each other on the x axis I would negate their x speed (v.x v.x). Now, this isn't very realistic, so, how do I do it? All objects are rectangles represented by x, y, w, h vectors. Objects can't rotate.
18
Keep running CGRectIntersect Method Objective C I have two UIImageViews. mainSprite, and enemy1. And I have a method that makes enemy1 start moving towards mainSprite. So here's that method. (void)enemy1Aggro if (CGRectIntersectsRect(mainSprite.frame, enemy1Aggro.frame)) if (mainSprite.center.x gt enemy1.center.x) enemy1.center CGPointMake(enemy1.center.x 2, enemy1.center.y) if (mainSprite.center.x lt enemy1.center.x) enemy1.center CGPointMake(enemy1.center.x 2, enemy1.center.y) if (mainSprite.center.y gt enemy1.center.y) enemy1.center CGPointMake(enemy1.center.x, enemy1.center.y 2) if (mainSprite.center.y lt enemy1.center.y) enemy1.center CGPointMake(enemy1.center.x, enemy1.center.y 2) This works because I'm calling it on an IBAction that is a button that gets held down. But the problem is that when that button stops being pressed, this method stops running. So what I need is a way to have this method keep on running. Maybe a for loop? I'm not using anything like cocos2d, and I'm not using CoreGraphics. If you need to see any more of my code just ask. Thanks )
18
How are trajectories calculated and transmitted to other players, in multiplayer? I play a lot of "Call of Duty", and can see tracers for gunfire, missiles, care packages falling from helicopters etc. There is a lot of activity. I am curious to know the algorithm one would use, at a high level, to manage all this action when you have 20 people on a map shooting each other to death. This question touches on the subject, but doesn't ask for a more in depth answer as to how you the developers go about calculating and transmitting movement and collision detection for projectiles, be it missles, bullets, or any other object that is flying through the air in real time. How are trajectories calculated and transmitted to other players, in multiplayer?
18
Collision Responses with many different types I'd like to write an efficient Collision Response code, that does not use instanceof type checks that often (if possible) my current implementation is something like this GameObject.collidesWith(GameObject other) if(other instanceof ConcreteType1) do response with Concrete Type 1 else if (other instanceof ConcreteType2) do response with Concrete Type 2 GameObject is the base class of everything. Is there a possibility to avoid instanceof and type checks?
18
Does collision between two Area2D work differently than collision with Rigidbody2D? Consider a Main.tscn with (1) a player Player extends Area2D AnimatedSprite CollisionShape2D The player has func on Player body entered(body) hide() (2) a falling rock Rock extends RigidBody2D AnimatedSprite CollisionShape2D (3) a trap Trap extends Area2D AnimatedSprite CollisionShape2D The collision between Player and falling Rock (Area2D vs RigidBody2D) makes the player disappear as expected. While, the collision between Player and Trap (Area2D vs Area2D) does nothing. Is it expected?
18
Space efficient data structures for broad phase collision detection As far as I know, these are three types of data structures that can be used for collision detection broadphase Unsorted arrays Check every object againist every object O(n 2) time O(log n) space. It's so slow, it's useless if n isn't really small. for (i 1 i lt objects i ) for(j 0 j lt i j ) narrowPhase(i,j) Sorted arrays Sort the objects, so that you get O(n (2 1 k)) for k dimensions O(n 1.5) for 2d and O(n 1.67) for 3d and O(n) space. Assuming the space is 2D and sortedArray is sorted so that if the object begins in sortedArray i and another object ends at sortedArray i 1 they don't collide Heaps of stacks Divide the objects between a heap of stacks, so that you only have to check the bucket, its children and its parents O(n log n) time, but O(n 2) space. This is probably the most frequently used approach. Is there a way of having O(n log n) time with less space? When is it more efficient to use sorted arrays over heaps and vice versa?
18
Implementing Seperating Axis Theorem I'm trying to implement the Seperating Axis Theorem by following this article I found on MDN. Unfortunately, I'm not too geometry savvy and I wasn't able to find any good, simple implementation examples around the internet. I've tried to search for the specific concepts that the article mentions, but I'm not sure that I'm on the right track and I've got several doubts about this. Here's what I did so far export class Point constructor(x, y) this.x x this.y y rotate(pivot, angle) let s Math.sin(angle) let c Math.cos(angle) let p new Point(this.x pivot.x, this.y pivot.y) return new Point((p.x c p.y s) pivot.x, (p.x s p.y c) pivot.y) compare(point) todo import Point from quot . Point.js quot export class Line constructor(p1, p2) this.p1 p1 this.p2 p2 getSlope() return (this.p2.y this.p1.y) (this.p2.x this.p1.x) getNormal() let dx this.p2.x this.p1.x let dy this.p2.y this.p1.y return new Line(new Point( dy, dx), new Point(dy, dx)) getYIntercept() return this.p1.y this.getSlope() this.p1.x getPointProjection(point) let slope this.getSlope() let yIntercept this.getYIntercept() let slope2 1 slope let yIntercept2 point.y slope2 point.x let nx (yIntercept2 yIntercept) (slope slope2) return new Point(nx, (slope2 nx) yIntercept) import Point from quot . Point.js quot import Line from quot . Line.js quot export class Polygon constructor(...points) this.points points overlaps(polygon) let side new Line(this.points 0 , this.points 1 ) let axis side.getNormal() function findMinAndMaxProjectedPoints(polygon) polygon.points.forEach(point gt let projection axis.getPointProjection(point) ) Did I implement the various formulas correctly? How should I quot keep track of the highest and lowest values quot for each polygon? How am I supposed to determine which projected points are the lowest and which are the highest? How do I check for gaps between the highest and lowest projected point of the two polygons?
18
Meaning of offset in pygame Mask.overlap methods I have a situation in which two rectangles collide, and I have to detect how much did they collide so I can redraw the objects in a way that they are only touching each other's edges. It's a situation in which a moving ball should hit a completely unmovable wall and instantly stop moving. Since the ball sometimes moves multiple pixels per screen refresh, it is possible that it enters the wall with more than half its surface when the collision is detected, in which case I want to shift its position back to the point where it only touches the edges of the wall. Here is the conceptual image it I decided to implement this with masks, and thought that I could supply the masks of both objects (wall and ball) and get the surface (as a square) of their intersection. However, there is also the offset parameter which I don't understand. Here are the docs for the method Mask.overlap Returns the point of intersection if the masks overlap with the given offset or None if it does not overlap. Mask.overlap(othermask, offset) gt x,y The overlap tests uses the following offsets (which may be negative) .. A yoffset .. B xoffset
18
2D Collision detection and design So, listening to this very smart piece of advice, I've already completed a basic Tetris game. Moving on, I started a small breakout. But suddenly a nightmare came. Collisions. Since I've been struggling with this a lot, I read a bunch of article of the web. Being a beginner, I thought that, in the first approach, I would only use Rectangle to detect collisions. Right. Now I still have some problems. First of all, all the articles I stumbled upon on the Internet told me how to detect collisions, e.g. checking if objects A and B collided with each other. But it is not what I really need. In order to respond properly, I need to tell my objects if the collision happened on the X or Y axis and then setting the new velocity according to some rules. The problem is that there are so many possibilities when making the distinction between types of collisions that I don't think I've taken the right path. The second point (which, I believe, is really tied with the first) is the pattern in which the detection and the resolution of a collision happen. Right now, I have a CollidableObject classes and a CollisionDetector classes which knows about these objects. Each frame, the detector is looking for collision (or at least for me, is trying) and when he finds one, it alerts each collided object, saying "Hey you ! You've have collided with Z on the X axis, change that velocity now." and the object abides. The main issue right now is that I can detect the collision axis and therefore, when saying "Hey you ! You collided !", I cannot respond properly. In which direction should my velocity change ? I've been thinking a lot about this lately, trying to figure it out on my own, but I haven't find something that I liked so I am asking here now. Thank you for your answers ! (Note I don't know if this is relevant, but I'm coding in C using SDL)
18
most efficient AABB vs Ray collision algorithms Is there a known 'most efficient' algorithm for AABB vs Ray collision detection? I recently stumbled accross Arvo's AABB vs Sphere collision algorithm, and I am wondering if there is a similarly noteworthy algorithm for this. One must have condition for this algorithm is that I need to have the option of querying the result for the distance from the ray's origin to the point of collision. having said this, if there is another, faster algorithm which does not return distance, then in addition to posting one that does, also posting that algorithm would be very helpful indeed. Please also state what the function's return argument is, and how you use it to return distance or a 'no collision' case. For example, does it have an out parameter for the distance as well as a bool return value? or does it simply return a float with the distance, vs a value of 1 for no collision? (For those that don't know AABB Axis Aligned Bounding Box)
18
SAT test for Triangle convex hull I'm having real trouble resolving this issue with triangle convex hull SAT test intersection. The problem is as follows Misses are detected accurately enough Clear miss I have not found a problem with false negatives (ie collision is there but not detected). But I do have a problem with false positives (collision detected even though there is not one) Appears to detect false This only happens occasionally with orientations like the one shown (that is actually a pretty big gap). What I'm doing conceptually is just a usual SAT test for the triangle against the hull. I'm pretending the single triangle is a "convex hull", indeed it might be if you imagine it is a very thin, very flat tetrahedron. I don't know if I am mistaken in this concept of triangle convex hull intersection, if the slight inaccuracy is to be expected, or if there is perhaps a bug in my code (the same SAT Test routines work for hull hull, box hull, and other test quite accurately though) The relevant code is at line 621 of hull.h, with the SATTest overlap routine in Intersectable.cpp.
18
Resolving Circle Circle collision If you have a stationary circle with radius x, and a moving circle with radius y, when a collision is detected, how can you resolve the collision, such that the moving circle stop? I.e. What would be the 'resolved' position of the moving circle?
18
Does it matter who does the collision detection? I gave an answer to How to decide which GameObject should handle the collision?, and received a lot of negative feedback on it, claiming that it does not matter who does the collision detection. I am not understanding that stance. For example There are 100 bullets and 1 player on the screen. Let's assume brute force collision detection and no optimization such as layers or references. If the collision detection is done by the bullet, each bullet must detect for collision on 100 different objects. That's 100 x 100 detections, for 10000 detections total. If the player does the detection, that's 100 detections total, one for each bullet. Am I mistaken? If so, what am I missing?
18
How to detect collision between a camera and a mesh? I am wondering how you would be able to extract mesh properties (i.e. faces, vertices, and vertex normals) and use them to create a collidable object, one that a camera can't go through ? I am using TheCodingUniverse's OBJLoader. The files are in the episode 24 and utility folders.
18
Libgdx collision detection and response I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the Rectangle.overlaps method. In response I am trying to find out at what edge the player hits the tile and then react accordingly. Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile). I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since Rectangle.overlaps() is used I am only reacting to a collision already happening. Here the source private void resolveCollision() setUpPlayerRec(allObjects.get(0)) for (Rectangle r2 tiles) if (!playerRec.overlaps(r2)) continue else onCollisionWithTile(r2) private void onCollisionWithTile(Rectangle r2) Gdx.app.log("Collision Detected", "Player collided with tile") float diff if (playerRec.x playerRec.width lt r2.x) LEFT EDGE OF TILE controlledPlayer.getPosition().x (r2.x playerRec.width) controlledPlayer.getVelocity().x 0 else if (playerRec.x gt r2.x r2.width) RIGHT EDGE OF TILE controlledPlayer.getPosition().x (r2.x r2.width) controlledPlayer.getVelocity().x 0 if (playerRec.y lt r2.y) HIT TOP OF TILE diff (playerRec.y playerRec.height) r2.y controlledPlayer.getPosition().y Math.abs(diff) jumptime MAXJUMP controlledPlayer.setJumpState(JUMP STATE.GROUNDED) else if (playerRec.y lt r2.y r2.height) HIT BOTTOM OF TILE controlledPlayer.setJumpState(JUMP STATE.GROUNDED) jumptime 0 diff playerRec.y (r2.y r2.height) controlledPlayer.getPosition().y r2.y r2.height
18
How can I perform 2D side scroller collision checks in a tile based map? I am trying to create a game where you have a player that can move horizontally and jump. It's kind of like Mario but it isn't a side scroller. I'm using a 2D array to implement a tile map. My problem is that I don't understand how to check for collisions using this implementation. After spending about two weeks thinking about it, I've got two possible solutions, but both of them have some problems. Let's say that my map is defined by the following tiles 0 sky 1 player 2 ground The data for the map itself might look like 00000 10002 22022 For solution 1, I'd move the player (the 1) a complete tile and update the map directly. This make the collision easy because you can check if the player is touching the ground simply by looking at the tile directly below the player x and y are the tile coordinates of the player. The tile origin is the upper left. if (grid x y 1 2) The player is standing on top of a ground tile. The problem with this approach is that the player moves in discrete tile steps, so the animation isn't smooth. For solution 2, I thought about moving the player via pixel coordinates and not updating the tile map. This will make the animation much smoother because I have a smaller movement unit per frame. However, this means I can't really accurately store the player in the tile map because sometimes he would logically be between two tiles. But the bigger problem here is that I think the only way to check for collision is to use Java's intersection method, which means the player would need to be at least a single pixel "into" the ground to register collision, and that won't look good. How can I solve this problem?
18
3D collision for non mathematician I am having an extremely hard time understanding smooth 3D collision. I have spent a month trying to figure out the math and still cannot get perfect collision detection that perform the same way as in games such as Quake. I've resorted to a virtual 2D rectangle collision model applied to 3D plane, but it's full of bugs and doesn't handle slopes. It seems that very complex math is required like matrices and vectors. There are lots of tutorials online but they are full of mathematical symbols and it's impossible for a math novice like me to understand it, I also don't have time to go through a mathematics basics from the beginning. Is it possible to do collision without vectors or matrices or a guide somewhere that can explain in non mathematical terms how to implement smooth collision? How can a nonmathematician overcome 3D math?
18
My collision detection is not working when I rotate my mesh in three.js I am trying to move a ball mesh through a maze. The maze belongs to a parent object3d. My issue is that when I move the ball I can't detect collision right well because in the rotation, the axis relative to the ball are changing and for some reason I can't control the collisions with the wall. Here is my code This function detects collisions function collisionControl() var colision false Checking collisions with the ball var originPoint bola.position.clone() I get the position of the ball relative to the maze( puzzle) var globalPositionPoint originPoint.applyMatrix4(puzzle.matrix) for (var vertexIndex 0 vertexIndex lt bola.geometry.vertices.length vertexIndex ) var localVertex bola.geometry.vertices vertexIndex .clone() var globalVertex localVertex.applyMatrix4(bola.matrix) var directionVector globalVertex.sub(bola.position) var ray new THREE.Raycaster(globalPositionPoint, directionVector.clone().normalize()) var collisionResults ray.intersectObjects(collidableMeshList) if (collisionResults.length gt 0 amp amp collisionResults 0 .distance lt directionVector.length()) if (collisionResults 0 .object.name "fin") location.reload() Si encontramos una colision, la bola vuelve a su lugar origen colision true break return colision The function RotacionEje Function to rotate the ball function RotacionEje(object, axis, radians) var rotWorldMatrix new THREE.Matrix4() rotWorldMatrix.makeRotationAxis(axis.normalize(), radians) rotWorldMatrix.multiply(object.matrix) object.matrix rotWorldMatrix object.rotation.setFromRotationMatrix(object.matrix) So when I press the Up arrow for example it executes, the following function function moveUp() bola.position.z 0.5 RotacionEje(bola, ejeX, 0.1) camera.translateY(0.5) if (collisionControl()) bola.position.set(47.5, 0, 50) camera.position.x 47.5 camera.position.y 0 camera.position.z 100 camera.lookAt(bola.position) I have to say that collisions works fine if I don't use the function RotacionEje. What am I doing wrong?
18
Why does the player fall down when in between platforms? Tile based platformer I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER FRAME event. It's only for collision from the bottom for now. var i int var j int var platform Platform var playerX int player.x 20 var playerY int player.y 20 var xLoopStart int (player.x player.width) 20 var yLoopStart int (player.y player.height) 20 var xLoopEnd int (player.x player.width) 20 var yLoopEnd int (player.y player.height) 20 var vy Number player.vy 20 var hitDirection String for(i yLoopStart i lt yLoopEnd i ) for(j xLoopStart j lt xLoopStart j ) if(platforms i 36 j ! null amp amp platforms i 36 j ! 0) platform platforms i 36 j if(player.hitTestObject(platform) amp amp i gt playerY) hitDirection "bottom" This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.
18
How to get rid of an image upon collision detection in SDL? I am fairly new to SDL in C, but I have written a simple game whereby a character has to reach the end of a level and avoid bad stars on the way. If he hits a star, he dies. There are also good stars he can collect and get points. I have set up my point system so now when he hits a good star, he should get a point. However, when he hits a star, he actually gets lots of points, as long as he is touching the star, which I don't want. I think that what's happening is because the stars are moving and he rubs up against the stars each pixel he moves counts as a new collision so he gets a point per collision. Ideally, he should only get one point per star. So I have two problems 1) I need to figure out how to make it so that he can only get one point when he hits a star. 2) Since he is supposed to be 'collecting' the stars, I want to make the star disappear when he collects it. So it's similar to most of these types of games, whereby, the player collects something, it disappears and they get a point. EDIT This is struct I've made typedef struct int x, y, w, h, baseX, baseY, mode float phase Goodstar I've then referenced it in another struct like so Goodstar goodStars GOOD STARS SDL Texture goodStar GOOD STARS is equal to 100. And then here's my collision detection code Check for collision with good stars for (int i 0 i lt GOOD STARS i ) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points break So right now it only checks for a collision and then adds a point. EDIT 2 This is the code you suggested and it works for (int i 0 i lt GOOD STARS i ) if (!game gt goodStars i .awarded) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points game gt goodStars i .awarded 1 break And this is my initialisation code Initialise stars for (int i 0 i lt GOOD STARS i ) game gt goodStars i .baseX 320 random() 38400 game gt goodStars i .baseY random() 480 game gt goodStars i .mode random() 2 game gt goodStars i .phase 2 3.14 (random() 360) 360.0f game gt goodStars i .awarded 0
18
Collision detection using distance field for a dynamic object I am using a signed distance field for collision detection. The object I calculated the distance field for rotates between 0 and 30 degrees. The other object I want to check collision against is in a bounding volume hierarchy (BVH) of axis aligned boxes. The problem is that as the first object is rotating, I cannot use the initial calculated distance field for collision detection. One solution that I thought of is that I can rotate the Bounding volumes by an angle opposite to what the original object rotates and then check the collision but this can be computationally extensive. Is there any other better solution that I can use to check the collision with the rotating object?
18
How do I efficiently perform collision detection on an NxN rectangle grid? I have a simple level that is constructed from an NxN rectangle grid. Some of the rectangles are walls, and some of them are the path. The player is allowed to move only on the path they are on and also the path rectangles on the grid. So I have two kinds of rectangles in the grid "path" "wall" The player is a sprite above the grid. I want to efficiently find if the player is colliding with the wall. I want to loop through the rectangles, to see if they intersect. What is the best method?
18
OnTriggerEnter OnTriggerStay triggers multiple times and is not been call a second time I am working on a feature that when the Player pass thru a door, a message will popup on the screen. I'm having few problems Debug.Log gives me from 2 to 6 logs when I pass thru the collider plane and when I come back to the same collider plane the script it is not been call a second time. What I'm trying to achive is that Debug.Log gives me only one log and every time I pass thru the collider the script runs again. so here is my code function OnTriggerEnter (other Collider) OnTriggerStay gives the same result if (other.tag "Player") isColliding true else isColliding false function OnGUI() if (isColliding) Debug.Log(isColliding) Application.ExternalCall('hive.OpenHiveAlert', 'test') function OnTriggerExit() Destroy(this) Any help would be appreciated, thanks.
18
LWJGL Collision Detection I cannot find LWJGL collision detection with a camera and walls. Like making it to where you can not walk through walls and other different shaped rectangular prisms and cubes. How do I set up LWJGL collision?
18
Collision detection using distance field for a dynamic object I am using a signed distance field for collision detection. The object I calculated the distance field for rotates between 0 and 30 degrees. The other object I want to check collision against is in a bounding volume hierarchy (BVH) of axis aligned boxes. The problem is that as the first object is rotating, I cannot use the initial calculated distance field for collision detection. One solution that I thought of is that I can rotate the Bounding volumes by an angle opposite to what the original object rotates and then check the collision but this can be computationally extensive. Is there any other better solution that I can use to check the collision with the rotating object?
18
body entered signal won't emit when rigidbody collided to rigidbody I have multiple rigidbody object floating away in the space. When they hit each other, they push away each. I want to destroy object if they hit something, but connect body entered signal won't invoked when they impact each other func ready() connect("body entered", self, "destroy") func destroy(body) print("HIT!") queue free() How do I check Rigidbody hit something?
18
2D narrow phase line intersection with square bounding box for calculating height efficiently I've performed partitioning of my level into broad and narrow phase. I'm down to narrow phase and focusing on the height from the ground. I want to see what polygon the player is on top of. Since some polygon sectors may be lower than others (this is a birds eye view), I want the player to be stand on top of the highest one. Therefore I thought what I can do is each game tick would be to check which boxes the player intersects, and then find the polygon with the highest 'height' and use that as the base height for the player. An example would be below Is this a viable way of doing it? That this game is 3D, but I only have to do two dimensional calculations for the height which reduces the computation and makes this easier. The level has been cut up into a BSP tree so the following is a gross misrepresentation of the level, however I don't see any obvious way (immediately) to exploit the BST property to find out the highest sector that the player would be standing in. So far the best way I could think of was to use narrow phase collision detection described above and hope that is extremely fast. I am looking for speed here, so if you know of any better algorithms or some faster way of doing this, please let me know. EDIT The focus of this post is for high level algorithms, of which they can be optimized later on. No actual collision detection code has been made yet.
18
Fast self collision intersection detection algorithm for tetrahedral meshes I want to play with deformation of tetrahedral mesh (soft body simulation) but I need help with self collision detection stuff. I found SOFA collision detection but I'm not sure that it fits for self intersection of a tetrahedral mesh. Can anyone suggest me good algorithm for self collision detection? As far as I can understand, something like BVH of tetrahedra can help me, but it would be great if somebody with expertise shows me right direction.
18
How does a collision engine work? How exactly does a collision engine work? This is an extremely broad question. What code keeps things bouncing against each other, what code makes the player walk into a wall instead of walk through the wall? How does the code constantly refresh the players position and objects position to keep gravity and collision working as it should? If you don't know what a collision engine is, basically it's generally used in platform games to make the player acutally hit walls and the like. There's the 2D type and the 3D type, but they all accomplish the same thing collision. So, what keeps a collision engine ticking?
18
How to destroy bullet on collision but only after it makes the collided object to bounce? I made a scenario that shooting a bullets on crates make them both bounce nicely (both the bullet and crates are RigidBody2D amp Colliders). When I use OnCollisionEnter2D to destroy the bullet when it hits the crate then the bullet destroyed before it pass the force to the crate and thus the crate stay still and not move physically... How to make the crate move because of the bullet hit and also make the bullet to destroyed? There is more elegant way from just destroy the bullet a frame after the hit?
18
Using Lazer with a Quadtree I have a quadtree implementation that works well with what I need for handling collisions between enemies, projectiles, and heroes. However, most of these types of entities are pointbased, with varying radius but that's about it. I have a weapon idea for lazer or ray weapon that's essentially a line. How does something like that fit in to working with something like a quadtree? Normally when we have a quadtree, we are essentially letting that data structure handle point masses to figure out which subset of objects we need. How then might we handle something like a line? The dumb way to do it is to just query the enemies and do something like a circle line intersection test on all the enemy objects. This is obviously not efficient especially when we already have a quadtree. One idea i have are to just put some dummy projectile object along the line and submit those to the quadtree. Then if we get any returned objects from those dummies, then we can use the circle line intersection test on it. Any ideas pertaining to how to use ray weapon that requires some line intersection test with a quadtree would be appreciated. Thanks.
18
Question about BoundingSpheres and Ray intersections I'm working on a XNA project (not really a game) and I'm having some trouble with picking algorithm. I have a few types of 3D models that I draw to the screen, and one of them is a switch. So I'm trying to make a picking algorithm that would enable the user to click on the switch and that would trigger some other function. The problem is that the BoundingSphere.Intersect() method always returns null as result. This is the code I'm using In the declaration section Basic matrices private Matrix world Matrix.CreateTranslation(new Vector3(0, 0, 0)) private Matrix view Matrix.CreateLookAt(new Vector3(10, 10, 10), new Vector3(0, 0, 0), Vector3.UnitY) private Matrix projection Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f 600f, 0.01f, 100f) Collision detection variables Viewport mainViewport List lt BoundingSphere gt spheres new List lt BoundingSphere gt () Ray ControlRay Vector3 nearPoint, farPoint, nearPlane, farPlane, direction And then in the Update method nearPlane new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 0.0f) farPlane new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 10.0f) nearPoint GraphicsDevice.Viewport.Unproject(nearPlane, projection, view, world) farPoint GraphicsDevice.Viewport.Unproject(farPlane, projection, view, world) direction farPoint nearPoint direction.Normalize() ControlRay new Ray(nearPoint, direction) if (spheres.Count ! 0) for (int i 0 i lt spheres.Count i ) if (spheres i .Intersects(ControlRay) ! null) Window.Title spheres i .Center.ToString() else Window.Title "Empty" The "spheres" list gets filled when the 3D object data gets loaded (I read it from a .txt file). For every object marked as switch (I use simple numbers to determine which object is to be drawn), a BoundingSphere is created (center is on the coordinates of the 3D object, and the diameter is always the same), and added to the list. The objects are drawn normally (and spheres.Count is not 0), I can see them on the screen, but the Window title always says "Empty" (of course this is just for testing purposes, I will add the real function when I get positive results) meaning that there is no intersection between the ControlRay and any of the bounding spheres. I think that my basic matrices (world, view and projection) are making some problems, but I cant figure out what. Please help.
18
Finding if a point is inside of a mesh (Point in polyhedron) How can I find if a point (Vector3) is inside of a mesh? Would this work for both concave and convex objects? I read somewhere that if you raycast in both directions of every axis (X, X, Y, Y, Z, Z), take the count of the hits, and if it is even it is outside, if it is odd it is inside. I tried this and it didn't work.
18
Swift How do I detect the exact point at which two "SKPhysicsBody(edgeFromPoint " type physics bodies intersect in sprite kit I have two physics bodies attached to two separate sprite nodes using Sprit Kit. One is a vertical line and one is a horizontal line sprite with horizontal physics body spriteMatrix i j .physicsBody SKPhysicsBody(edgeFromPoint CGPointMake(0, tileSegmentHeight), toPoint CGPointMake(tileSegmentWidth, tileSegmentHeight)) spriteMatrix i j .physicsBody!.categoryBitMask self.surfaceCatagory spriteMatrix i j .physicsBody!.contactTestBitMask heroCatagory sprite with vertical physics body self.hero.physicsBody SKPhysicsBody(edgeFromPoint CGPointMake(self.hero.frame.width 2, self.hero.frame.height 2), toPoint CGPointMake(self.hero.frame.width 2, 20)) self.hero.physicsBody!.categoryBitMask heroCatagory self.hero.physicsBody!.contactTestBitMask surfaceCatagory What I'm want to do is test if they are intersecting on every frame, and if they are, return the x and y position of where they are intersecting. Is this even possible?
18
Collision detection with moving objects I searched a lot about this problem. I found many answers here in Stack Exchange but none of them really answers when positions for objects get updated. For a game with fixed size map and that has all the time 200 moving objects with different sizes (bullets, players, NPCs, etc.) 100 static objects with different sizes (obstacles, health packs, etc.) I am looking for an efficient way to do collision detection. Here is the pseudo code in each game loop (15 ms) collect movement commands and apply force on objects of those commands loop with very small physics time steps (0.1 ms) for object in movingObjects get objects that might collide with current object gt 1 check if any collision occurs for object in movingObjects update position of object (based on command collected) gt 2 So I get the objects that might collide with given object. It is done using a data structure like quadtree or spatial hashing grid (or something else that makes more sense). Object's position is updated. Now, how do I inform the data structure that this object's position is updated? I don't want to remove and insert. That is not efficient at all. I feel like quad tree and spatial hash implementations all over the internet are avoiding this problem. I would also appreciate if you tell me my pseudo code above is problematic. I have the feeling this uses too much CPU.
18
What kind of physics to choose for our arcade 3D MMO? We're creating an action MMO using Three.js (WebGL) with an arcadish feel, and implementing physics for it has been a pain in the butt. Our game has a terrain where the character will walk on, and in the future 3D objects (a house, a tree, etc) that will have collisions. In terms of complexity, the physics engine should be like World of Warcraft. We don't need friction, bouncing behaviour or anything more complex like joints, etc. Just gravity. I have managed to implement terrain physics so far by casting a ray downwards, but it does not take into account possible 3D objects. Note that these 3D objects need to have convex collisions, so our artists create a 3D house and the player can walk inside but can't walk through the walls. How do I implement proper collision detection with 3D objects like in World of Warcraft? Do I need an advanced physics engine? I read about Physijs which looks cool, but I fear that it may be overkill to implement that for our game. Also, how does WoW do it? Do they have a separate raycasting system for the terrain? Or do they treat the terrain like any other convex mesh? A screenshot of our game so far
18
Python collision problem I have a hero character with jumping physics that I am trying to figure out the collision detection for. Right now, the problem that I am running into is as soon as the character hits the floor (while I'm pressing left on the left side of the screen) the rect that it recognizes that it is colliding with is the ground. Which is to be expected. However, based on the checks that I have, for sprite in self.group.sprites() wall collide sprite.feet.collidelist(self.walls) if wall collide gt 1 print wall collide if self.col ground(sprite, wall collide) self.hero.jumping False sprite.move back y(dt) if self.col left(sprite, wall collide) sprite.move back x(dt) if self.col right(sprite, wall collide) sprite.move back x(dt) print quot quot since the character is colliding with the ground, the check to see if the character's rect is inside the colliding rect fails for 2 reasons 1 The current collision rect is the ground which the character is above, so the test fails 2 Because of 1, the character will keep moving left until it realizes it's colliding with the left side, at which point it will have already gone too far into the wall. What's the best collision solution? Note the character starts to the right of the left wall, on the ground but isn't colliding with the ground since the start position is right above it. Also, I realize that my code is a bit jumbled and I'm not taking care of every sprite in the group. I'll fix that once I have this fixed. I can provide more code pictures if necessary Edit More code def col ground(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midbottom) return True return False def col left(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midleft) return True return False def col right(self, sprite, wall) if self.walls wall .collidepoint(sprite.feet.midright) return True return False
18
How to go about an intermediate collision resolution system? I would like to know a better way of collision resolution than I am currently doing. My current collision system stores the current positions and previous positions of each object. When an object collides with another it sets the current positions to the previous positions. This would work fine if objects could only move in four directions, but when they can move in more than four directions the system doesn't work. For example if you are moving an object A up and right and it collides with and object B above it, the object A stops moving even if still going up and right. In most 2d games however if this scenario happened the object A would stop moving up but continue to move right. This is the kind of collision resolution that I would like to implement. I don't need anymore complicated physics right now this will do. I'm just using rectangles so that would be the only shape I need to worry about.
18
given the position and velocity of an object how can I detect possible Collision? I'm trying to detect Collision between autonomous moving objects and steer direction if collision is detected. so far I've been following a tutorial and I'm having a hard time to fully understand how it works especially the role of the dot product foreach (GameObject t in targets) get me all moving agents Vector3 relativePos Agent targetAgent t.GetComponent lt Agent gt () access properties like velocity relativePos t.transform.position transform.position Vector3 relativeVel targetAgent.velocity agent.velocity float relativeSpeed relativeVel.magnitude can someone explain this part of code how did we calculate the time of collision? float timeToCollision Vector3.Dot(relativePos, relativeVel) timeToCollision relativeSpeed relativeSpeed 1 float distance relativePos.magnitude float minSeparation distance relativeSpeed timeToCollision
18
How to use collision masks and overlap area in pygame? So, I've been prototyping a game, and I've been using sprite collision, and it's not cutting it any more. I read up on the documentation about masks and overlap area https www.pygame.org docs ref mask.html pygame.mask.Mask.overlap area How exactly do I use this? The documentation says "This can be used to see in which direction things collide, or to see how much the two masks collide. An approximate collision normal can be found by calculating the gradient of the overlap area through the finite difference." I don't quite follow this description. How can I tell the direction of the collision? What does the return value actually contain? How would I implement this collision for two Pygame Sprites with images and transparency? Is there a more in depth explanation (preferably with sample code) anywhere? I can't find anything more detailed than the documentation.
18
Collision Filtering in Box2D I have four bodies in my Box2D World. Each are polygon shape, with some physics parameters. Now when the game start, I need one of the bodies from the World (BodyA) to not be allowed to collide with another (BodyB). It should be allowed to collide with others. To clarify, BodyA and BodyB cannot collide with each other, but can collide with rest of the bodies in the Box2D world. How could make this kind of mechanism in Box2d ? Please help me about this query. Thanks amp Regards,
18
What would be an efficient way to check if there is a collision in a 2d game? As part of my final project of Algorithms and Data Structures, we have to develop an open world game in C . I already got developed most of the game, but I haven't coded the collisions with the enemies. First, I'll explain how the game works. It's an open world game, where there are 10 regions. The world is a big map, where only a small portion of it has to be visualized in the screen . The world is 40 screens x 40 screens, where each screen is 1900 x 1080 pixels. In this world, there are 250 000 enemies that are distributed in all the regions, so that each region has 25 000 enemies. Besides, there is a main character that has to travel around this world doing missions, collecting items and killing enemies. Now, my problems raises here, what is the most efficiency way to check if the main character collides with any enemy, so that when he attacks this enemy and kill him I can eliminate the enemy from the world? In order to solve this problem, I assigned each region a list of enemies, so that the amount of enemies to validates reduces significantly. I also have a function that returns the region where the main character is. Then, to check for collisions I do this for ( Number of Enemies in the Region) if ( MainCharacter is colliding with an Enemy and MainCharacter kills the Enemy) delete Enemy from the Region I think this way is pretty inefficient since I have to validate all the enemies in the region and I just want to validate the enemies that are closer to the main character or are visible in the screen. How should I improve the collision detection so that it's more efficient? I hope I made my self clear and I would really appreciate any help you can provide.
18
Spatial Hashing is set up.. now how should I go about actual collision logic? So I have a spatial hashing system set up and it works. It puts players in buckets based on their x y width height So I was going to check collisions on each frame when I loop through the entity for updating their physics. But how would I go about duplicate collisions? Say I'm checking for player a, which is in the same bucket as bullet a.. I check if there's a collision and there is, should I do the collision logic right there? Or should I add the collision to a list and iterate through that list at the end of the frame to handle the logic for each collision? This way I can also apply logic to prevent duplicate collisions. Or should I just do all the logic right there and then when the initial collision is made?
18
Collision detection for sloping tiles I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out. First, some background. My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen). So, my 'slope tile' looks something like this Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think. Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile. I then multiply that by my slope (slope being height width or 100 102 in my case) I then divide by 2 to get the centre Finally, I subtract that result from the height of the tile (to invert it) This gives me the vertical center which I can compare with the centre of my sprite to check for collision. So, my code looks like this VertTileCentre Math.round(tileYCoord tile.quadHeight ((slope (spriteX tileX)) 2)) Results When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly. Edit 1 results from further experimenting I've noticed that the sprite when at the top left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up because it was hitting solid blocks behind (which have their own collision detection) Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) therefore if I remove the solid blocks, it works OK. So I have no idea why not dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!
18
3D Binary Space Partitioning with solid empty leaves I've recently started looking into BSPs for real time collision detection, and I'm now looking into improving the performance of my solution. The system that I've implemented is rather similar to the solution found on wikipedia (https en.wikipedia.org wiki Binary space partitioning), where each node contains triangles found located on the node's hyperplane, and references to two nodes found on each side of the hyperplane. BSP generation pseudocode Node generate bsp(Trimesh mesh) Trimesh back, front Node node(mesh 0 ) Generates the plane position and normal of the node loop (Triangle tri mesh) if (onPlane(tri, node)) node.triangles.add(tri) else if (inFront(tri, node)) front.add(tri) else if (Behind(tri, node)) back.add(tri) Not fully in front or behind means that the triangle is found on both sides and needs to be split else Triangle trisSplit tri.split(node) loop (tri2 trisSplit) if (inFront(tri2, node)) front.add(tri) else if (Behind(tri2, node)) back.add(tri) node.nodeBack generate bsp(back) node.nodeFront generate bsp(front) return node This means that for a raycast, I iterate over the hyperplanes sorted from front to back, and determine if my ray hits any of the triangles found on each hyperplane. BSP raycast pseudocode Bool ray intersect bsp(Vector rayPos, Vector rayDir, Node BSP) if (BSP null) return false if (onPlane(rayPos, node)) if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true else if (inFront(rayPos, node)) if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true else if (ray intersect bsp(rayPos, rayDir, BSP gt nodeBack)) return true if (ray intersect triangles(rayPos, rayDir, BSP gt triangles)) return true if (ray intersect bsp(rayPos, rayDir, BSP gt nodeFront)) return true return false This system however demands using ray triangle intersection determination, which is a costly procedure. What makes matters worse is that there's a high chance that the triangles you iterate on are missed by the ray, which results in a relatively large amount of costly raycasts that need to be performed before finding the closest hit on the trimesh. What methods can I use to optimize my BSP structure and traversal?
18
LWJGL Collision Detection I cannot find LWJGL collision detection with a camera and walls. Like making it to where you can not walk through walls and other different shaped rectangular prisms and cubes. How do I set up LWJGL collision?