_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
18 | Bounding Volumes for Empty Space I'm creating an Android game that relies heavily on collision detection for a couple of players (at least up to 4). I researched hierarchical structures that could speed up the process. Because I have worked with hierarchies of axis aligned bounding boxes for ray tracing in uni, the sweep and prune algorithm is currently my favorite choice. However, I had the idea to use bounding boxes not only for the obstacles in a level, but also some boxes containing as much of the free space in the scene as possible. If the player's character stays within one of those during his movement between two frames no further intersection tests should be necessary. Could this approach reduce the number of intersection checks where a player's character intersects one or more axis aligned boxes but not the objects within? I highly doubt I am the first person who thought of this, yet I didn't find something like it online. So, is there a good reason not to do this? My best guess for why it isn't done is that there is no good rule to find applicable bounding boxes for empty spaces in between. But if they are precomputed before the game I don't see this as a problem. Maybe they could be bounding spheres instead. Those could be grown from an obstacle's surface until it touches obstacles in at least three points, like so Any advice would be greatly appreciated |
18 | Clip shadow frustum to scene bounds I have a global light in my scene. It casts shadows using shadow mapping and has an associated camera (for rendering to the shadow map). I'm going to refer to it as my "shadow camera" from now on. I need to find a way to place my shadow camera's near plane as close as possible to my scene's bounding box (clip it to the scene bounds). I need to do this so the shadow casters are never clipped by the shadow camera's near plane (otherwise I'd get holes inside of shadows) and to make sure I don't accidentally cull any shadow casters behind the camera. This would also allow me to increase the shadow mapping precision, because it lets me move the near and far planes closer together. Example 1 (possible to do using a simple plane check) Example 2 (NOT possible to do using a simple plane check) The black box is the scene's AABB (but it would be nice if this would work for OBBs or other shapes too). The yellow arrow represents the light direction. The green box is the shadow camera's frustum without any modifications. The red box is my desired result. At the moment I'm constructing the red box by projecting the black box onto the global light's direction vector and use the closest vertex's distance to compute the shadow camera's near plane. But this makes it impossible to get something as seen in the 2nd image. Instead the red box starts above the scene's AABB. I have thought of using SAT for this, but it doesn't seem to be the solution. |
18 | Is it possible to have concurrent collision detection where every entity acts at exactly the same time? There are many algorithms that can be used for collision detection. In many cases we check for an overlap in coordinates of an entity. If we make a triangle a,b and c. We have 2 entities at a and b heading for a collision at c but each of them are moving at exactly the same time, what kind of algorithm could work? It seems more like a chess game where you would have to predict every move that the other entity would have to make, if they swerve to the left to avoid a collision will they also run the chance to collide. Is it possible or is it too complex? Would it work for thousands and millions of entities in the same search space? |
18 | Exact collision time of two axis aligned bounding boxes I am trying to calculate the exact collision time of two axis aligned bounding boxes (aabb) as fast as possible (in the sense of CPU time). I have all the required information (aabb min, max, center, etc., velocity vector, and so on) My aabbs are not rotating, so they have linear velocity The aabbs can be both moving, only one of them might be moving, or they both might be steady My current approach creates lines from one of the boxes' corners and checks the collision among the planes of the other box (you can see the algorithm below) however it takes 6 times longer than I can afford. So, I am trying to find a faster algorithm however, I couldn't have managed, yet. My current quot slow quot algorithm Add velocity of Aaabb to Baabb and assume Aaabb is steady and Baabb is moving Calculate the corner positions of Baabb For each corner of Baabb, perform the line plane intersection with Aaabb's each 6 planes (I use the line intersection formulate (algebraic form) on Wikipedia) to check if there is an intersection. If a corner of Baabb intersects with a plane of Aaabb, verify the intersection point is behind the other 5 planes of Aaabb Keep the smallest value of d and return |
18 | Fast(er(est)) fullscreen scene collision detection technique ("selection buffer") My vertex format has a float4 Flags element used to pass miscellaneous data to shaders. Each mouse collidable object that is rendered has a unique ObjectID that is written to an ObjectID rendertarget which can be CPU sampled to index the hovered object. The remaining render targets are geometry lighting data. I've found this has advantages I set (Flags.x ObjectID) upon object creation so the vertex buffer only needs an initial upload and updates only when new ObjectID's (that will be rendered) are created. Everything else is per object instance. Essentially, "no" overhead added by using a Flags component for ObjectID. I'm semi certain that, since I have to render everything anyway, outputting one additional color to one additional rendertarget is already cheaper than ANY clever bounding container collision testing algorithm. Currently, I copy the entire ObjectID rendertarget back to the CPU, but even that could be further optimized. The depth buffer (that I'm using anyway) automatically ensures that the pixel I sample is the ObjectID of the top most, visible, mouse collidable, object. I don't have to check if the mouse position ray is within the bounds of anything, intersects with anything, visibilities, nothing. All of that is already sorted out by rendering the scene properly. Rendering the interface components first and reusing the ObjectID depth buffer to render the world, reduces the fill volume for the 3D scene drastically, if a lot of interface is visible. I've found only one disadvantage Since I render the interface first, if the camera has moved (the world hasn't been rendered yet), the WorldCoordinate available during Update() is incorrect. If the camera hasn't changed, the coordinate is correct. Immediately after rendering to the geometry buffers, but before any cursor dependent shaders are invoked, I update the CPU buffer and WorldCoordinate. The CPU buffer is only updated when necessary and, at most, once per frame. The "second sample" is during the following Update() and just re reads the (wrong if the camera has moved) value from the byte array. Still, no significant overhead and this is basically just a slight annoyance because I'm just debugging the value anyway. Currently, when the WorldCoordinate is usefully used (during render), it is correct. Overall, I've got pixel perfect, anything on the screen, mouse collision detection, with zero additional overhead beyond standard rendering. Minimal and or approximately fixed, regardless of screen scene complexity Why is this method not popular and or tutorialized? I assume most new ish games post process geometry buffers but I found nothing similar to this and just worked my way through the issues as they came up. To me, it appears as though I've got collision detection working for all of the objects classes that I haven't even written yet. All of the "tech" involved here is obvious and easy, so I feel like I must be missing something a future problem that I can't think of yet. Comments critiques of the "algorithm" are welcome. Best answers would point out critical flaw(s) and, for bonus points, work arounds. If this has been done before, is there an accepted best practice? Links to similars would be ok. |
18 | How can I reproduce the physics that we can see in Dawn of Titans? I'm working on a hobby RTS project and I want to implement collision physics between soldiers like in the mobile game Dawn of Titans. Here is a video reference https youtu.be Fnpot2NeJl8?t 341 How can I achieve this? |
18 | Collisions with complex assets from Blender in SceneKit I have a very basic workflow question I'm prototyping a game with Apple's SceneKit framework. It can automatically create a mesh for collision detection, but it will always be a convex hull. This works okay for simple meshes, but now I want my character wo walk into a house. The options I could come up with Use the same mesh for the physicsShape (could be too complex and a performance bottleneck) Build the level in SceneKit and only create atomic building blocks in Blender Create a second low poly version of the model and use that for collisions (basically twice the work? As you can see I have zero experience with game development and best practices. What is the typical way to do this? |
18 | Collision Detection point hitting a rotating rectangle Im developing a game which has a flying chopper and an enemy firing bullets at it. Whats the best way to detect when the bullet hits the bounds of the chopper. The chopper is placed to the left of screen, continously rotating around its center. Bullet is fired from the right, always in a straight line. Im using Marix post rotate and translate for the choppers rotation.To make it simpler, I just want to consider the chopper to be a rectangle. Lets say im not bothered about any more precision in terms of specific hit points. |
18 | Creating Complex Collision Shapes in GMS2 I'm pretty new to Game Maker Studio 2 and I've hit a wall in programming with their built in physics engine. I created a irregularly shaped object and I want to modify the collision shape so that it fits the shape of the sprite. In the built in collision shape editor it only allows you to create a convex shape with a max of 8 points. Is there another way to do this without having to plot out points individually in code? Thanks! |
18 | What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? Provided that both objects have rectangular hitboxes, x and y positions and height width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? No engine is being used. |
18 | Collision detection circle segment segment I've already implemented collision detection in my game loosely following this tutorial, which works great, but I realized there's one major flaw. The player and the enemies are circles, while the obstacles can be either segments or polygons or circles. Now, let's say I have segment A from point (100, 100) to point (300, 100) and segment B from point (100, 200) to point (300, 100), which means they form an acute angle, and player has it center in point (100, 125), with a radius of 25. If player starts moving right, it will eventually collide against segment B. My method checkCollisions() will return a vector, but if I apply that vector on player, it will be moved up and left, and will overlap segment A. If I call checkCollisions() a second time, player will be pushed down and collide again with segment B, so recursive invocations aren't a solution. Any ideas? Here's a picture to explain The g n vector direction is along the bisector of the two little vectors, but how do I find the length? |
18 | 2d Tile Based Collision Response Right now I am trying to make a 2d collision response system for a platformer, and the algorithm I have for it works quite well. The only problem is that if the player is standing exactly on a tile, he cannot move. I think this is related to the fact that the manager is checking if he is colliding on the X axis, instead of the Y Axis. I have thought of making one big AABB for a check, using all applicable tiles, but I feel as if there is a simpler way. I don't really understand normals, so I have not tried anything with them yet. Right now, I am getting the centers of both objects, the distance inbetween them, and the minimum distance between them, returning the overlap. And then applying the overlap to the players position. It looks like this sf Vector2f centerA( AABBFirst.left (AABBFirst.width 2), AABBFirst.top (AABBFirst.height 2)) sf Vector2f centerB( AABBSecond.left (AABBSecond.width 2), AABBSecond.top (AABBSecond.height 2)) sf Vector2f distance(centerA.x centerB.x, centerA.y centerB.y) sf Vector2f minDistance( (AABBFirst.width 2) (AABBSecond.width 2), (AABBFirst.height 2) (AABBSecond.height 2)) return sf Vector2f( distance.x gt 0 ? minDistance.x distance.x minDistance.x distance.x, distance.y gt 0 ? minDistance.y distance.y minDistance.y distance.y) I apologize if this question has already been asked and answered before, I have not found the proper terms to search for. |
18 | Is there a specific library to handle the collision system of a big game world like WoW, or any physics library will work? Nothing else to add. Is there a specific library to handle the collision system of a big game world like WoW, or any physics library like ODE will work? |
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 | Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles |
18 | 2D physics collision gravity problem? I'm using Love2D and my own physics engine to create a 2D platformer. Y collision works fine, but X collision... well, it's a bit buggy. When I move off of a small platform I've created, I fall but it is a lot slower than what my gravity is set to. Here's my code for collision function world.collisionCheck(o) for k, v in pairs(world.objects) do if v o then if v.Type "Rectangle" and o.Type "Rectangle" then if o.Position.Y (o.Size.Y 2) gt v.Position.Y (v.Size.Y 2) then o.Velocity.Y 0 o.onGround true end if not (o.Position.X (o.Size.X 2) gt v.Position.X and o.Position.X (o.Size.X 2) lt v.Position.X (v.Size.X)) then o.onGround false end right left end end end end As you can see, it's pretty bad. The code for the actual physics (gravity, movement, etc.) is a bit better function world.update(t) for k, v in pairs(world.objects) do if v.Static true then v.Position.X v.Position.X v.Velocity.X if v.onGround false then if v.Velocity.Y lt world.Gravity then v.Velocity.Y v.Velocity.Y world.Gravity t end end v.Position.X v.Position.X v.Velocity.X world.Meter v.Position.Y v.Position.Y v.Velocity.Y world.Meter v.Velocity.X v.Velocity.X world.Friction world.collisionCheck(v) end end end However, it could still use some work. Whenever I step off of a 150 pixel by 15 pixel platform, I fall a lot slower than 9.8 meters per second. My meters are set to two pixels, and I'm falling at about a meter per second, which is much slower than the expected 20 pixels per second I get while still on the platform. Everything I've tried doesn't seem to fix it there's no problem in the movement code, and nothing I change in the collision code seems to fix it. Is there some silly problem I've overlooked? EDIT Okay, so I implemented a small fix which somewhat solves my problem. I modified the collision code so that it checks if it is below what is being tested for collision, and it seems to accelerate as normal when the top of the object is below the object being collided with, and vice versa. Am I correct in assuming I just need to add something to detect if the x value is in the correct range, too? |
18 | Play an effect where a sprite touches a trigger I have a sprite based GameObject in Unity to which is attached a RigidBody and a Collider2D. When this GameObject comes into contact with a particular Collider2D Trigger, I want a particle effect to play at the point of contact. This sounds extremely simple to set up and yet I can't seem to find any solution that works, since OnTriggerEnter2D doesn't bother to provide hit coordinates. Please note that the trigger represents a non solid space, so adding a solid (non trigger) collider for hit detection is not a solution. The sprite is large, so I can't just play the particle effect at its transform position. Raycast is not an appropriate solution for this problem it doesn't handle nearly enough cases. |
18 | How to design Client server hybrid hit detection with projectile weapons? Hybrid hit detection here refers to a architecture where client sends a hit claim to server and server verifies it with a tolerable error limit to confirm the hit or deny it. This technique may work well with hit scan or instant hit weapons because you only have to check it for one frame tick. But in case its a physics projectile I.e where an actual projectile flies to the target like a real bullet, the hit is the result of flight over more than one frames and varying physics state. As such verifying the hit could be very cumbersome and resource intensive. So how would one go for server client hybrid approach in this scenario? |
18 | Voxel terrain collision detection with AABBs I'm working on implementing collision detection on voxel terrain (Like Minecraft) with AABBS. Right now, I have it so I can tell if a point is within a voxel or not, I do this by having a 2D byte array of active voxels. If a byte at any index is 0, the voxel is air. If its 1, its solid. Right now I'm just testing to see if the voxel at the player's position vector is solid or not. My problem is, I now wish to implement AABBs to get more precise detection, but I have no idea how to do it without checking if all the voxels within the AABB are solid. That might now be a problem for games like Minecraft, where there would only have to be about 1 extra voxel check, but the voxels in my game are much smaller (The player's dimensions are about 4x10x4), so I would have to check a lot of voxels. Ive seen one or two other people having a issue similar, but I didn't find the answers they got clear enough, and so I come here asking for your help. Thanks. |
18 | OBB vs OBB Collision Detection Say you have two Bounding Box Objects each of them storing the current vertices of the box in a vector with all the vertices of the object rotated and translated relative to a common axis. Here is an image to illustrate my problem How can I work out if the two OBB's are overlapping any links to help explain the solution to the problem would be welcome. Nothing too convoluted please... |
18 | What is the fastest way to work out 2D bounding box intersection? Assume that each Box object has the properties x, y, width, height and have their origin at their center, and that neither the objects nor the bounding boxes rotate. |
18 | How to represent a game character in code? In a previous game I wrote I had a game character class. This class tracked the location, velocity, and a set of states. Except the states were tied very close to the animation. Each state would have a list of buttons that can transition it other states, and an animation that would go with that state (you could also do per frame animation state changes, if you wanted to do something like have a very specifically timed punch or something). All of the collision data for the character was done on a per animation frame basis. This was done for a fighting game, so it seemed necessary at the time to have the animation and collision tied so closely to the character state. But the programmer in me feels like this is mixing responsibilities. And now I'm making a game engine that I want to be a little bit more generic than that. How do you typically organize the structures relating to the characters, how they're drawn, how they interact with each other and the world, etc? I realize this is sort of a vague question that depends on the type of game I want to make, but I think seeing how other people handle this would be useful. (and if it matters, this is all for a 2D game.) |
18 | Updating physics for animated models For a new game we have do set up a scene with a minimum of 30 bone animated models.(shooter) The problem is that the update process for the animated models takes too long. Thats what I do Each character has 30 bones and for every update tick the animation gets calculated and every bone fires a event with the new matrix. The physics receives the event with the new matrix and updates the collision shape for that bone. The time that it takes to build the animation isn't that bad (0.2ms for 30 Bones 6ms for 30 models). But the main problem is that the physic engine (Bullet) uses a diffrent matrix for transformation and so its necessary to convert it. Code for matrix conversion ( 0.005ms) btTransform CLEAR PHYSICS API Mat to btTransform( Mat mat ) btMatrix3x3 bulletRotation btVector3 bulletPosition XMFLOAT4X4 matData mat.GetStorage() copy rotation matrix for ( int row 0 row lt 3 row ) for ( int column 0 column lt 3 column ) bulletRotation row column matData.m column row for ( int column 0 column lt 3 column ) bulletPosition column matData.m 3 column return btTransform( bulletRotation, bulletPosition ) The function for updating the transform(Physic) void CLEAR PHYSICS API BulletPhysics VKinematicMove(Mat mat, ActorId aid) if ( btRigidBody const body FindActorBody( aid ) ) btTransform tmp Mat to btTransform( mat ) body gt setWorldTransform( tmp ) The real problem is the function FindActorBody(id) ActorIDToBulletActorMap const iterator found m actorBodies.find( id ) if ( found ! m actorBodies.end() ) return found gt second All physic actors are stored in m actorBodies and thats why the updating process takes to long. But I have no idea how I could avoid this. Friendly greedings, Mathias |
18 | How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this? |
18 | Detecting collision between a sprite and many tiles I have been looking at the following question Tile coordinates and am thinking of using this for collision detection in my tile game. The set up in my game is similar to this, in that there is a grid of tiles, and the sprite will move to (x,y) coordinates. However, if I were to have an object such as a box in my world that is made from multiple tiles, how would I get the collision detection to work? Any ideas welcome. |
18 | 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 | Gravity and collision detection interfering with player movement I am attempting to implement collision detection for a 2d sidescroller game and I'm having trouble keeping gravity from interfering with player movement. Every frame I get and handle input, creating values for a point that represents the players movement vector. I then add gravity to the vector and check for collisions. This is the way AI will be handled as well. The problem I'm having is when the player is on a floor tile, even if the input says to walk horizontally, after I add gravity to the move vector, collision detection returns a collision so the movement is completely negated. I know i can test which a is is the problem, negate that and move the player but then if I change the players movement vector inside collision testing, wouldn't I have to cull for collisions again based off the new move vector? I don't know if this has to do with input handling or collision testing. So how should I go about adding gravity to the players movement? |
18 | Unit collision avoidance for RTS I'm developing an RTS, and having a little difficulty with collision detection. From what I understand RTS generally don't bother with collision detection and just try to avoid collision, and that is what I am trying to accomplish. My game uses a grid for static obstacles, but units are not bound to the grid for movement. How do I allow for units to avoid collisions, both with static obstacles and with other units? Right now my workaround is to redirect units around static obstacles every time they move from point to point (and every time a new obstruction is placed on map, units replan their routes). This doesn't seem like an ideal solution, but it works. I have no idea how to handle unit unit collisions. |
18 | How to detect collisions in AS3? I'm trying to make a simple game, when the ball falls into certain block, you win. Mechanics The ball falls through several obstacles, in the end there are two blocks, if the ball touches the left block you win, the next level will contain more blocks and less space between them. Test the movie (click on the screen to drop the ball) http gabrielmeono.com downloads Lucky Hit Alpha.swf These are the main variables var winBox QuickObject You win var looseBox QuickObject You loose var gameBall QuickObject Ball dropped Question How do I trigger a collision function if the ball hits the winBox? (Win message Next level) Thanks, here is the full code package import flash.display.MovieClip import com.actionsnippet.qbox. import flash.events.MouseEvent SWF(width 600, height 600, frameRate 60) public class LuckyHit extends MovieClip public var sim QuickBox2D var winBox QuickObject var looseBox QuickObject var gameBall QuickObject Constructor public function LuckyHit() sim new QuickBox2D(this) sim.createStageWalls() winBox sim.addBox( x 5,y 600 30, width 300 30, height 10 30, density 0 ) looseBox sim.addBox( x 15,y 600 30, width 300 30, height 10 30, density 0 ) make obstacles for (var i int 0 i lt (stage.stageWidth 50) i ) End sim.addCircle( x 1 i 1.5, y 16, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 15, radius 0.1, density 0 ) Mid End sim.addCircle( x 0 i 2, y 14, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 13, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 12, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 11, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 10, radius 0.1, density 0 ) Middle Start sim.addCircle( x 0 i 1.5, y 09, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 08, radius 0.1, density 0 ) sim.addCircle( x 0 i 1.5, y 07, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 06, radius 0.1, density 0 ) sim.start() stage.addEventListener(MouseEvent.CLICK, clicked) .. param e MouseEvent.CLICK private function clicked(e MouseEvent) gameBall sim.addCircle( x (mouseX 30), y (1), radius 0.25, density 5 ) |
18 | Collision Detection for a 2D RPG First of all, I have done some research on this topic before asking, and I'm asking this question as a mean to get some opinions on this topic, so I don't make a decision only on my own, but taking into account other people's experience as well. I'm starting a 2D online RPG project. I am using SFML for graphics and input and I'm creating a basic game structure and all for the game, creating modules for each part of the game. Well, let me get to the point I just wanted to give you guys some context. I want to decide on how I'm going to work with collision detection. Well I'm kinda going to work on maps with a tile map divided in layers (as usual) and add an extra 2 layers not exactly in the map for objects. So I'll have collisions between objects and agents (players npcs monsters spells etc) and agents and tiles. The seconds one can be easily solved the first one need a little bit of work. I considered both creating a basic collision test engine using polygons and a quadtree to diminish tests since I'm going to be working with big maps with lots of objects creating both a physical and graphical world representation. And I also considered using a physics engine like Box2D for collision tests. I think the first approach would take more work on my part but the second one would have the overhead of using a whole physics engine for just collision detection and no physics. What do you guys think ? |
18 | Bounding volume hierarchy linked nodes (linear model) The scenario A chain of points (Pi)i 0,N where Pi is linked to its direct neighbours (Pi 1 and Pi 1). The goal perform efficient collision detection between any two, non adjacent links (PiPi 1) vs. (PjPj 1). The question it's highly recommended in all works treating this subject of collision detection to use a broad phase and to implement it via a bounding volume hierarchy. For a chain made out of Pi nodes, it can look like this I imagine the big blue sphere to contain all links, the green half of them, the reds a quarter and so on (the picture is not accurate, but it's there to help understand the question). What I do not understand is How can such a hierarchy speed up computations between segments collision pairs if one has to update it for a deformable linear object such as a chain wire etc. each frame? More clearly, what is the actual principle of collision detection broad phases in this particular case how can it work when the actual computation of bounding spheres is in itself a time consuming task and has to be done (since the geometry changes) in each frame update? I think I am missing a key point if we look at the picture where the chain is in a spiral pose, we see that most spheres are already contained within half of others or do intersect them.. it's odd if this is the way it should work. |
18 | Libgdx how to store every single point drawn using touchdragged? Basically i am trying to detect line collision. The problem is when intersection occurs quickly(touch dragged is done quickly like fling), the collision is not detected. It seems as if 'touch dragged' doesn't store all points. |
18 | Without using a pre built physics engine, how can I implement 3D collision detection from scratch? I want to tackle some basic 3D collision detection and was wondering how engines handle this and give you a pretty interface and make it so easy... I want to do it all myself, however. 2D collision detection is extremely simple and can be done multiple ways that even beginner programmers could think up When the pixels touch when a rectangle range is exceeded when a pixel object is detected near another one in a pixel based rendering engine. But 3D is different with one dimension, but complex in many more so... what are the general, basic understanding examples on how 3D collision detection can be implemented? Think two shaded, OpenGL cubes that are moved next to each other with a simple OpenGL rendering context and keyboard events. |
18 | How to detect collisions in AS3? I'm trying to make a simple game, when the ball falls into certain block, you win. Mechanics The ball falls through several obstacles, in the end there are two blocks, if the ball touches the left block you win, the next level will contain more blocks and less space between them. Test the movie (click on the screen to drop the ball) http gabrielmeono.com downloads Lucky Hit Alpha.swf These are the main variables var winBox QuickObject You win var looseBox QuickObject You loose var gameBall QuickObject Ball dropped Question How do I trigger a collision function if the ball hits the winBox? (Win message Next level) Thanks, here is the full code package import flash.display.MovieClip import com.actionsnippet.qbox. import flash.events.MouseEvent SWF(width 600, height 600, frameRate 60) public class LuckyHit extends MovieClip public var sim QuickBox2D var winBox QuickObject var looseBox QuickObject var gameBall QuickObject Constructor public function LuckyHit() sim new QuickBox2D(this) sim.createStageWalls() winBox sim.addBox( x 5,y 600 30, width 300 30, height 10 30, density 0 ) looseBox sim.addBox( x 15,y 600 30, width 300 30, height 10 30, density 0 ) make obstacles for (var i int 0 i lt (stage.stageWidth 50) i ) End sim.addCircle( x 1 i 1.5, y 16, radius 0.1, density 0 ) sim.addCircle( x 2 i 1.5, y 15, radius 0.1, density 0 ) Mid End sim.addCircle( x 0 i 2, y 14, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 13, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 12, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 11, radius 0.1, density 0 ) sim.addCircle( x 0 i 2, y 10, radius 0.1, density 0 ) Middle Start sim.addCircle( x 0 i 1.5, y 09, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 08, radius 0.1, density 0 ) sim.addCircle( x 0 i 1.5, y 07, radius 0.1, density 0 ) sim.addCircle( x 1 i 1.5, y 06, radius 0.1, density 0 ) sim.start() stage.addEventListener(MouseEvent.CLICK, clicked) .. param e MouseEvent.CLICK private function clicked(e MouseEvent) gameBall sim.addCircle( x (mouseX 30), y (1), radius 0.25, density 5 ) |
18 | Changing speed of an object Is there a way of changing speed of an object at certain time? I want to change my speed to my initial speed after colliding with any object. I have already added bounce Physics to my colliding objects and player object with Friction set to 0. Please help. |
18 | How does the SAT collision detection algorithm work There are a lot of tutorials and sample code available showing how to implement the SAT collision detection algorithm. But can someone explain, without math or code, what are the general principls behind this technique. |
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 | Box2D Efficient method to create b2Chainshapes for a tile based map? I'm working on a platforming game with tile based levels. I store the collision model for my tileset in an array. This is how the collision model for a 4x4 tilesheet would look like (I can't post pictures yet so this link will have to suffice Tileset example). The red dots are the vertices of the b2ChainShape. When I load a level, I look up the collision model for each tile and create a b2Body at the corresponding place. The problem is that between the tiles, my character can experience a "bump" because it gets stuck on the edge of the shape of the next tile's body. Is there an existing algorithm to connect the bodies of neighbouring tiles to a single b2ChainShape? Or should I ditch the idea of tile based collision models all together and simply create the collision model for the whole map with the Tiled map editor? I don't create the the collision map with the Tiled map editor at the moment, because it is very time consuming for slopes and hills. |
18 | Unity mesh collider detecting collision on object empty inside I'm trying to get my first 3D game done with Unity. In this game the character will be flying through some rings. I made the ring asset with MagicaVoxel, exported it in .obj and reimported in Unity withouth problems. I've set a rigidbody and a box collider on the character model and a mesh collider withouth rigidbody to the ring and I've also set Convex and added the default mesh of the ring. The problem is that whenever I try to go inside the ring, I can't because I collide even with the empty part inside it. I'm not sure on how to made Unity collide only with the external part, but as far as I can see in the editor I'm using, I've no setting for it. I'm using Unity 5.3.4f1. Can someone please explain me how to solve this problem? Thank you very much. EDIT I'm sorry, I forgot to mention that I'm aware I can unset the ring mesh Convex property and get it to work. The problem of this solution, though, is that whenever I put adjacent rings I can glitch through them even if there's no space to fit. So basically I need a solid collider with Convex only on the external part of the ring and with empty space to fly through on the inside. Is this possible somehow? |
18 | What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? Provided that both objects have rectangular hitboxes, x and y positions and height width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination? No engine is being used. |
18 | How to do one way collision? I would like to know how can I do one way collision. It's the collision common in mario's games and many platforms. I try to do an code but I cannot post because it's part of a paid game. Basically I have two rectangles like this struct Rect int x, y positions in the world int w, h width and height The rect A moves and the rect B is fixed with the world. Someone has a idea of how to do this? |
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 | Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles |
18 | How client movement prediction syncs with server position to avoid a clip around collision? I have searched a lot on stackexchange and on google, yet I have not found a satisfactory answer to this seemingly simple question. I am making an online multiplayer game where the players navigate a 2d map with basic square obstacles. In this case I am making collision checks both on the client and the server, where the server broadcast everyone's position once per second as authority. However, when making a sharp turn around a square, often times either the client makes the turn while the server clips, or the client clips at the corner while the server makes the turn. That is understandable considering the possible discrepancy between the position on the server and the predictive position of the client. How do online multiplayer games usually work around this simple yet crucial problem? I understand that it comes down to a pixel perfect sync which isn't possible, but how do other games navigate around this issue, to give a flawless collision experience? What I am considering of doing Increase the position broadcasting rate from 1 time per second to however high needed to accurately sync the positions (20 sec). I believe this is the solution most games are doing. This however, will drastically increases the load on the server. In my case, the game's main mechanism isn't the navigation (think MMO), so I am leaning towards only checking collision on the client side, and have a simpler collision check on the server to ban walk through wall hackers. This would relax the server from heavy collision operations which is nice too. |
18 | How do I detect collisions between a particle based net and a ball? I've implemented a net using Verlet integration and many points connected with constrains like this demo, but in 3D. I want to implement collision detection between this net and a ball (like in a soccer game), so the net catches the ball. I've tried checking for collisions between the ball and net points (treating each like a small sphere), and this somewhat affects the net, but the ball passes through the gaps between points easily. How should I be approaching this? |
18 | Lerping character moving up and down slope tiles So, when interpolating position against a standard 'horizontal' platform, everything works great. What happens is something like this..... (Question continues after graphic) Now, the question I have is, how do we correctly interpolate the player's sprite (blue circle) against a 45 tile? When I attempt to do this, what happens, is that when the player is going up the slope, it is slightly embedded in the tile and when coming down the slope, it floats slightly above the tile. In the example above, the sprite effectively 'stops' moving along the Y Axis, so therefore, interpolation along that axis stops, however when interpolating the position against a slope, the sprite moves in an X and Y direction, so never stops. I think this is causing the issue, if my logic is correct, some more graphics follow to illustrate what I mean.... What am I doing wrong? How do I interpolate my sprite while making sure it's 'on' the slope at all times? For moving up a slope When moving down slope Summary When interpolating against a horizontal platform, although the sprite isn't rendered on the platform in the frame straight after collision has been resolved, it is rendered on the platform during subsequent frames because the difference between the old and new positions has become 0 as it is no longer moving. However against a slope, again, the initial frame is incorrect but then the sprite moves again, so the next frame is also wrong etc so it never 'settles'. Note it does move at the slope's angle just not on the slope. I'm trying to work out how to get my two points along the 45 slope and interpolate between them (ie, along the slope).... |
18 | Simple (and fast) dices physics I'm programming a throw of 5 dices in Actionscript 3 AwayPhysics (BulletPhysics port). I had a lot of fun tweaking frictions, masses etc. and in the end I found best results with more physics ticks per frame. Currently I use 10 ticks per frame (1 60 s) and it's OK, though I see a difference in plus for 20 ticks. Even though it's only 5 cubes (dices) in a box (or a floor with 3 walls really) I can't simulate 20 ticks in a frame and keep FPS at 60 on a medium aged PC. That's why I decided to precompute frames for animation, finishing it in around 1700 ticks in 2 seconds. The flash player is freezed for these 2 seconds, and I'm afraid that this result will be more of a 5 seconds or even more, if I'll simulate multi threading and compute frames in background of some other heavy processes and CPU drawing (dices is only a part of this game). Because I want both players to see dices roll in same way, I can't compute physics when having free resources, and build a buffer for at least one throw of each type (where type is number of dices thrown). I'm afraid players will see a "preparing dices........." message too often and for too long. I think the only solution to this problem is replacing PhysicsEngine with something simpler, or creating own physicsEngine. Do You have any formulas for cube cube and cube wall collision detection, and for calculating how their angular and linear velocities should change after a collision occurs? Edit I'm assuming the only way to solve my problem is to make a cube cube and cube wall collision engine, however maybe there's another solution for my problem. As Arthur pointer out, there can be one animation for me this is just a shortcut, I could as well show the final result without any dices rolling. However, I thought about making 100 precomputed dice throws, though a user won't avoid repetition here as well. Sometimes a dice sits on it's edge (or corner) for a while, and that gives player some excitement (will it fall on 5 and give me a full house?), but with limited number of animations a player would already know how the animation will end. Buffering solution would work, if players would see dices roll in different way (results would still be the same) I'm considering this solution, however I'm still going to try to create a simple physics engine and see how it works. less ticks is a solution I don't consider, because at as few ticks to be able to simulate physics in real time, the dices behave not better than if I treated them as balls in my physics engine... |
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 | How do I find the intersection of a ray and a cylinder? I'm looking for the algorithm to find the intersection (or lack of) between a ray and a cylinder. I have rotating coin like objects in my game world and need to check for a collision on that object. I also need to know the location of intersection to determine which part of the coin was hit. The cylinder has an arbitrary rotation. I can provide as input the direction (vector) it is facing, a centre point, and a radius. For the ray I can generalize to a line, as it'll be easy to check within the segment afterwards. Ideally I'd like the array to be an infinite cylinder, but I can easily fudge this aspect once I have the collision for a line. |
18 | How to retrieve vertex information from ID3DXMesh I need to know the position of each vertex (and triangles) from a mesh (a pointer to ID3DXMesh, created by calling functions like D3DXCreateBox, D3DXCreateTeapot and D3DXCreateSphere) to perform some collision detection. I've tried using GetVertexBuffer() and GetIndexBuffer() but I don't know how to use the structures to retrieve point data in the world coordinate system. How can I achieve that? |
18 | How can I implement rectangle collision response? I am working on a game in JavaScript and my current implementation of collision uses the shortest distance to push the intersecting object away, which isn't always correct. I've made this diagram of the ideal collision. The red box represents the starting position, the green box represents the proper position and the black box represents the static object it is colliding against. The blue arrow is the velocity vector. With my current implementation, the object would be placed in its final position and pushed out (and in this case it would be pushed left) How can I fix this? |
18 | Whats an elegant implementation for 2D collision detection in a block based game? to make things clear, i do not want to know HOW to implement collision detection mathematically. What i am looking for is an elegant way to check for collisions without having to manage seperate lists of objects, maybe for example implementing a ICollidable interface. currently i have a simple gameloop while(runGame) handleInput() update() render() So there are two possibilities which come straight to my mind. First, ill add an extra call to a method or class handling collisions. while(runGame) handleInput() update() checkCollisions() render() Second, every gameobject gets a list of nearby other objects in its update method. so it can do the collision on its own while(runGame) handleInput() update(otherNearShapes) render() i dont like both of these for two reasons. in the first, i have to manage a seperate list of objects which implement an ICollidable interface. in the second, the update method handles more logic than it should in my opinion. so, is there an elegant way of integrating collision detection in my game (loop)? searching the net always only results in how to calculate stuff, but thats not what i want to know. |
18 | My sprites do not always respect collisions in Pygame I have a Player sprite (40x40 pixels) and Tiles (20x20 pixels) which build the terrain. At the 4 edges there are 2 rows or columns (depends on vertical or horizontal) of wall tiles. Those are the limits which the player should not be able to overpass and collisions player wall are checked there. Most of times, it recognizes collisions, but sometimes it doesn't. When I move the player until the map limit and it hits the wall tile, it stops, but sometimes if I continue trying to move it against the wall, it doesn't respect the collision and enters in the wall. At this point, once the player enters in the wall tile it can only moves over wall tiles... So, am I doing something wrong or is it just a pygame collisions bug? Here is the method to check collisions def checkCollision(self) from prueba import limitGroup listLimits limitGroup.sprites() for i in range (0, len(listLimits)) if listLimits i .kind "wall" and self.rect.colliderect(listLimits i ) return True return False And here is the update() method to move the player. def update(self) for event in pygame.event.get() mouseX, mouseY pygame.mouse.get pos() if event.type pygame.MOUSEBUTTONDOWN self.bulletsGroup.add(Bullet(pygame.image.load("bullet.png"), self.rect.x (self.image.get width() 2), self.rect.y (self.image.get height() 2), mouseX, mouseY)) key pygame.key.get pressed() if key pygame.K RIGHT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K LEFT if not self.checkCollision() self.rect.x 10 else self.rect.x 10 if key pygame.K UP if not self.checkCollision() self.rect.y 10 else self.rect.y 10 if key pygame.K DOWN if not self.checkCollision() self.rect.y 10 else self.rect.y 10 |
18 | MMO Collision detection I am building a MMO game server for a 2D game and am currently implementing the collision detection, and I am would like to know what I should do. Lets say I have 1000 players playing and 10,000 objects, should I just iterate over them all to determine if colliding? This seems a bit pricey. I could separating the world into chunks and iterating every object for each player in it's chunk. I would like to know some other ideas or what is standard. What's the best way for a MMO server to handle collision detection with static objects? |
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 | Have the character automatically slide around obstacle corners Like this The player is only holding right, however the character still moves up a bit to go around an obstacle. My current collision system has access to The entity's previous position The entity's current position The entity's (axis aligned) bounding box All the obstacles and their (also axis aligned) bounding boxes Also it proccesses each axis separatelly. How can I implement this? |
18 | Can you help with collision detection and response in a 3D car racing game? I am trying to implement the collision detection and response in 3D car racing game. I have a car model, for collision I am assuming my car as a cuboid. my collision detection with walls is quite good and the response is also good. My model has a velocity, position, acceleration and orientation. I am using matrix to save the orientation and position. My problem is collision and its response with the ground (in my case it's road). When the ground is a simple plane with a constant y axis, then there is no need for collision detection as there is no force or movement in the y direction. But if my road is not linear, if it has some elevation, then I am having a collision detection problem when it comes to calculating its orientation. Any help and suggestions will be of great help. |
18 | Collision detection between draggable object and world objects? I have a game I'm making in Javascript that will involve combining items by dragging and dropping them onto each other. Think Alchemy or similar. So far, so good, but I hit a snag while trying to figure out how I can detect collisions between the two entities! I have a (really) basic bounding box test function isColliding(a, b) if (a.x a.width lt b.x a.x gt b.x b.width a.y a.height lt b.y a.y gt b.y b.height) return false else return true The trouble I'm having is that in practice, this is fine for detecting the mouse colliding with an object to pick it up, but I'm stuck on how I can, after I've grabbed an object, test to see if that object I have grabbed is colliding with any of the multiple other objects that exist in the window. I tried doing Core.objectCollision function() if (Core.Mouse.isHolding ! null) for (i in Core.Objects) if (isColliding(Core.Mouse.isHolding, Core.Objects i )) console.log("Colliding with world object!") This function is inside my update loop, but of course the object I'm holding is within my Core.Objects array too, so technically collides with itself. I really think I'm missing something obvious, but a lot of my searches for help have been returning how to simply detect collision between two already known items, however I need it so any item I grab can be tested against any other item in the view. Please also note I'm trying to avoid libraries for the time being, I'd rather learn the functionality myself. Thanks for any help! |
18 | How to handle interactions between a sprite (player) and another sprite? What's the proper way, a proper way, or any proper way at all, to handle interactions between a sprite (usually a player) and another sprite (can be any other object)? (in a tile based world) i.e. getting into a vehicle, talking with other character, reading signs, etc. My first instinct is to have some kind of "feeler" or interaction rectangle that's always in front of the player in the direction the player is facing. Then if that rectangle overlaps some kind of intractable object (driver door on vehicle, other character, sign, etc) I would be able to initiate an interaction. Is this a naive implementation? EDIT This is for a 2D engine, written in C for Xbox Live Arcade and Windows. |
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 | 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 do collision detection on marching cubes terrain? I'm writing the physics part of my game engine. The world uses the marching cubes algorithm on a 3d perlin noise to make the terrain. How do I do collision detection on the resulting mesh? I can't use SAT since the terrain is not convex and subdividing it into smaller convex parts seems to be nearly impossible. What is the best collision detection algorithm for such a mesh? The objects that are supposed to collide with the terrain can be any convex polyhedron. EDIT The terrain is not "cubed" (like minecracft). The terrain is smooth with slopes. This is pretty close to what my terrain looks like (this is NOT my video) https www.youtube.com watch?v 4rA3fdKWQA I am looking for a general collision detection here. I need the point(s) of contact and the normals so that I can put these into my collision resolver. Example of usage is throwing a box onto the terrain and it should roll and bounce approximately like it would in the real world. |
18 | Looking for collision detection algorithms for broad and narrow phases between non convex polyhedrons I have some experiences on particle system simulation (namely DEM Discrete element method), in which an individual particle with realistic shape (convex and non convex) is approximated by gluing 3D spheres together (non overlapping or overlapping), and act like rigid body. The collision detection is performed by the simplest sphere sphere contact. Nevertheless, for particle shape representing by polyhedrons, almost all the collision detection algorithms for broad and narrow phases are based on convex polyhedron (e.g. GJK). For non convex concave shapes, convex decomposition is required to divide the concave object into many convex components (e.g. V HACD). At this point, I really want to know the details on 1) how to store the concave objects via many convex components into memory (like BSP tree?) 2) collision detection and contact forces calculation between convex concave, concave concave objects. I have searched quite a few relevant books like "Real time collision detection" and "3D game engine design", etc, unfortunately I haven't find any details on this topic yet. Could some veteran game developers give some advice or insight on how to implement collision between concave objects? Cheers, David Update 1 Seems the physics engines likes Bullet3 and reactPhysics3D are able to simulate collision of non convex objects. Can someone give some rough idea on how to do this? before I dig into the source codes, since i have only some academic experiences on molecular dynamics DEM simulations mainly based on 3D spheres. |
18 | Proper sphere collision resolution? I am implementing a sphere to sphere collision resolution and I am a little confused on where to start. First question, is there a standard way that games engines do sphere to sphere collision resolution? Is there only like a couple standard ways to do it? Or does the resolution vary very heavily based on whats needed? I want to implement this in my engine and I wrote a basic one that pushes a sphere and another sphere (so basically the one interacting can push the other) but this was just a super simple concept. How exactly can I improve this to make it more accurate? (Mind you the code isn't optimized since I am still testing) It seems like there is a lack of solid documentation on collision resolution in general as it's a more niche topic. Most resources I found only concern the detection part. bool isSphereInsideSphere(glm vec3 sphere, float sphereRadius, glm vec3 otherSphere, float otherSphereRadius, Entity e1, Entity e2) float dist glm sqrt((sphere.x otherSphere.x) (sphere.x otherSphere.x) (sphere.y otherSphere.y) (sphere.y otherSphere.y) (sphere.z otherSphere.z) (sphere.z otherSphere.z)) if (dist lt (sphereRadius otherSphereRadius)) Push code e1 gt move( e1 gt xVelocity 2, 0, e1 gt zVelocity 2) e2 gt move(e1 gt xVelocity 2, 0, e1 gt zVelocity 2) return dist lt (sphereRadius otherSphereRadius) |
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 | 3D line segment AABB collision, with hit normal? I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily sized. I also need the surface normal of the AABB, if there was a hit. From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame. I have struct AABB VEC3F min VEC3F max a and b representing start end points of the line segment returns true if intersects, also fills out "normal" if true bool LineIntersectsAABB(const VEC3F amp a, const VEC3F amp b, const VEC3F amp inv dir, const AABB amp aabb, VEC3F normal) The implementations I've found either do not find the hit normal, and or they're intended for boxes cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations. |
18 | Custom Tile Collision Detection Has Trouble With Edges So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it). The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence http i.imgur.com CACfhIP.gifv I have narrowed this down to this specific segment of code (Please note that SPRITE WIDTH is 20, which also means 20 pixels) BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) round down to a multiple of SPRITE WIDTH else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) ditto but up The problem seems to be that both parts of the if...else if... statement require the equality symbol to work correctly. Meaning that in the provided example, the fall through glitch will happen to the tile on the left instead if I move the equality symbol to the else if portion. I attempted to fix this issue by adding an else clause and removing the equality from the if...else if... parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this BOOL changePos(Player player, Level level, int newX, int newY) int roundedY int roundedX if (newX lt player gt pos.x) roundedX roundDownTo(newX, SPRITE WIDTH) else if (newX gt player gt pos.x) roundedX roundUpTo(newX, SPRITE WIDTH) else if (newX SPRITE WIDTH gt SPRITE WIDTH 2) roundedX roundDownTo(newX, SPRITE WIDTH) else roundedX roundUpTo(newX, SPRITE WIDTH) But this created an even stranger case where the middle part of the tile would cause a fall through but the edges would work correctly on both the left and the right tile. This can be seen here http i.imgur.com lTaUuzh.gifv I've been at this all day (literally), I appreciate any help you can provide. If I have not provided enough information, please let me know and I will do my best to provide it. |
18 | Dodge different type of obstacles I'm writing a 2D game where the player has to kill a Ninja. This Ninja is coming closer with a constant speed chasing the player. The Map has some static obstacles like stones no one can pass. The player can move too and has different types of weapons to damage the Ninja in different ways Laser instantly on whole range Gun projectile (circular) following a fixed path Trap circular floor ability which detonates after time I want the Ninja to dodge those Weapons the best he can, he is allowed to take some damage, the least is preferred. I now have different ideas how to achieve that A with 3rd dimension (time) This is working but the paths are ugly and post processing is not my favorite. Also the Graph's size is about 1000x1000, making it inefficient (on creating neighbors), i try to reduce node count by scaling the nodes to unit.hitbox (40px), which drastically improves the calcs, but the paths look even more ugly.. Theta won't work even tho I love it, but line of sight on moving obstacles is... Visibility Graph same as Theta , moving obstacles... Steering haven't tried this one yet how it performs with constant speed and moving (, delayed) obstacles Local Avoidance won't work as the weapon speed is bigger than Ninja movement speed Geometry tangents, vector projection etc.... could work well if there aren't much obstacles to dodge Do you have any other ideas how to achieve some good doing for the poor Ninja? (NINJAS USUALLY DODGE EVERYTHING... That's why I also plan to give the Ninja a Ninja Roll feature he can use every 10s to dash on some position if he can't dodge something) Representation of the raw map (little dots are 40px) A Pathfinding with time dimension and a 5px Grid Edit I'll check out D Lite and RRT Smart Edit 2 Both are not what im looking for, i will try to optimize A |
18 | C Monogame Collision Detection Sprite walking through platforms I am blanking on the logic here. How do I get it so that my sprite doesn't run through a block. It only repels if the center of the player sprite is higher than the bottom of the block. But when it is lower, it walks right through. It gets lower because my jump function or my grounded function is a bit funky. Anyway, how do I get it so that a player can't go underneath a block unless the sprite is not touching the block at all. Here is the collision code in my player class, the one that does the collision detection. public void checkYCollisions(block platforms) if (position.Y gt 700) this is my ground with no blocks. grounded true else grounded false float Xradius Width 2 float Yradius Height 2 block collidedPlatform null List lt block gt collidedBlocks new List lt block gt () foreach (block p in platforms) if ((position.X gt (p.position.X p.Width 2 Xradius )) amp amp (position.X lt (p.position.X p.Width 2 Xradius )) amp amp (position.Y gt (p.position.Y p.Height 2 Yradius )) amp amp on top (position.Y lt (p.position.Y p.Height 2 Yradius ))) below collidedBlocks.Add(p) collisions work for all side of blocks. foreach (block p in collidedBlocks) if (p ! null) if ((position.Y lt (p.position.Y p.Height 2 radius ))) landing on a block grounded true else if ((position.Y gt (p.position.Y p.Height 2 Yradius ))) jumping up into a block if (y vel lt 0) y vel 1 player1.direction.Y 1.0f player1.direction.Y else if ((position.X lt (p.position.X p.Width 1.5 Xradius ))) one of the sides x vel 2 else if ((position.X gt (p.position.X p.Width 1.5 Xradius ))) other side x vel 2 Note that I have tried to remove YRadius in the the if loops at separate occurences, and it works to no avail because my guy will not hit the ceiling. |
18 | Swept AABB vs Line Segment 2D I've really exhausted as much as Google has to give, I've spent a solid week googling every combination of words for an "AABBvsLine sweep", downloaded countless collision demos, dissected SAT intersection examples and an AABBvsAABB sweep trying to figure out how to approach this. I've not found a single thing covering this specific pairing. Can anyone shed any light on how to get the hit time of a swept AABB vs a Line segment in 2D? I'm still getting familiar with the SAT but I do know how to implement it to a degree, I'm just not sure how to extract the hit time from the velocity in the non axis aligned separating axes for the sweep. I really would appreciate anything at the moment, some code or even some helpful links, I'm at my wits end! |
18 | How do physics engines like Box2D detect and respond to collisions between arbitrary polygons? I've always wondered how collision detection like this was achieved, and I've always wondered what the response would be. Do they perform line line intersection tests for each line making up the two polygons? If it'd make the question any more specific, how does Box2D handle this? |
18 | Determining which line to collide with I am making a platformer, where my player is represented as a circle and the ground is represented as lines. The actual collision detection and resolving works, it's just an edge case I can't find a solution for. I check on which line the hero is by using the normal, and if the hero's center is between these normals I know he is on that line. That works except for the case in the image above. When he get's in the 'Problematic Area' the algorithm will not detect any collision. So how do I know which line to pick for the collision when the hero get's in this area? Here is some code that shows how I test collisions (which again works, but does not consider the problem I actually have). playerPointer Vector2D New Vector2D(position.x line.x1, position.y line.y1) lineNormal Vector2D line.vector.Copy() lineNormal.LeftHandNormal() playerOnNormal Float playerPointer.ProjectionOn(lineNormal) playerOnLine Float playerPointer.ProjectionOn(line.vector) Do we have a collision between the circle and the infinite line If Abs(playerOnNormal) lt radius Get the direction vector of the line Local directionVector New Vector2D(line.x2 line.x1, line.y2 line.y1) Is the player inside the normals boundaries If (playerOnLine lt directionVector.Length) And (playerOnLine gt 0) |
18 | Implementing Separating Axis Theorem (SAT) and Minimum Translation Vector (MTV) I was following codezealot's tutorial on SAT and MTV and trying to implement it myself but I've come a cropper when it comes to getting the correct MTV. Here is my example (Cue pretty pictures...) I'm well aware how to obtain the length of the MTV and the axis on which it lies. However I can't work out whether the length should be 'positive' or 'negative' to push the object in the correct direction. In the example we are separating the objects by moving the 'red' of the 'blue', the top example is moving the object negatively and the bottom moving it positively. Please help I'm really struggling with this. Here is my actual implementation. |
18 | Unreal Engine 4.18 Knife (Weapon) collides with character capsule collision I have a character and he has a knife in his hand. When Run Walk action happens hands move and so does knife, its collision collides with character's capsule collision and causes issue in movement. More info Component Hierarchy looks like |
18 | Super mario bros "rounded" tile collision detection I'm working on a Mario bros clone with SDL and C (purely for educational porpuses and for fun) I got collision detection working by using AABB collision detection and resolving one axis at a time Check collision with X axis first Move entity if not collision is detected Check collision with the Y axis. Move entity if not collision is detected This is working great! However, one thing that I really like about the original Mario bros is that tiles have some kind of "rounded" feel to them. I think this helps make the map feel more organic, see how Mario moves left when jumping on a corner in the original SNES game I thought of using a circle collider for mario instead of an AABB. This would make Mario "fall" off the tiles if you step too close to the edges. But perhaps someone knows a better approach. I've been thinking about collision detection for longer than I'd like to admit. I'd love to know if someone has a clean aproach to accomplish what the GIF shows. |
18 | How to manage collision between balls in Game Maker 2 (Drag and Drop) Hey there I'm using Game Maker 2 Drag and Drop for a project, I made a game like Break Out and when the ball collides with the wall it doesn't bounce, in Game Maker Studio we had Bounce Action but in GMS2 is deleted, can anyone help me about this issue? |
18 | Intersection of thick line with a grid There is a popular paper, and numerous examples, on how to efficiently perform collision detection for a line with a grid. However, I'm drawing up blanks on how to do the same thing but with a line that has thickness. In my game, I'm considering adding projectiles that are not infinitly thin (for example, a giant plasma ball launcher), and I need to figure out which cells along a grid that it collides with. Initially I thought it'd be as simple as just using the Minkowski Sum method of adding the width height of the projectile to each cell of the grid, and then treating the projectile as infinity thin line along a bloated overlapping grid, but that doesn't look like it's going to work with the existing algorithm. Are there any other papers algorithms that describe how to accomplish this? Or is there a way to modify the existing algorithm to accomplish this? Or are there any tricks to implementing this indirectly? |
18 | Adding Leniency to Jumping Mechanic I have written some jumping code for my player in a platformer game. At the moment it has some basic logic which says that the player can jump if he is on the ground. The pseudocode looks something like this Input Handling if(jumpButtonPressed) if(onGround) jump Player Update Loop onGround false movePlayer resolveCollisions if(player collided with ground) onGround true This works fine for basic static tile levels, but when the player is standing on a descending platform, or moving down a downward slope for instance, it becomes very difficult to jump. The reason for this (in the case of the descending platform) is that the platform has moved from underneath him in that frame, so for that moment he is not actually colliding with the ground, and therefore the condition to be able to jump is not fulfilled. Is there a general way to add some leniency into the jump mechanic so that the player can jump even if they are not technically on the ground for that exact frame? This seems like it should be quite a common problem but I cannot seem to find any similar questions on stackexchange or google. |
18 | Collision detected at different times depending on speed? Imagine a scenario where there are four cubes. Two blacks that do not move, one red moving at a constant speed of two (2) straight and the other blue moving at a constant speed of five (5) also straight. They all have equal bounding boxes. By doing a test, I realized that if I put a command so that as soon as the red cube strikes against the black it turns left, the command does not run as soon as they collide ... With the blue he wanted him to turn right as soon as he hit. The command takes longer to happen, I think because it is faster than red ... Illustration of the incident It seems that the faster the object is, the longer it responds to the collision command. I would like you to give me a solution to this problem. I've already moved with some bounding box options, but nothing that has given the desired result. I also moved at the speed of the room, but it did not work either. Sorry for any translation error. Thanks in advance! |
18 | Directional, Triangular Collision Detection in Pygame I am trying to create a game in Pygame, with Python 3, and am trying to figure out an algorithm that will tell me which direction a rectangle is colliding with a rectangle, so that I can push it back the correct direction. I know I can detect rect to rect, and I could (possibly?) use pixel to pixel collision, but I was wondering if there was a better way. My collision algorithm currently loops through all of the "entity" objects in a Pygame sprite.Group(), and testing for collision using the colliderect() method, then I test which direction the rect is coming from by testing which sides overlap. Is there something similar that I could do with a collision between a triangle and a rectangle, too? Pseudocode would be nice. |
18 | 3D collision detection middleware (I've split this question into two. For 2D, see 2D collision detection middleware) Are there any recommendable middleware available for 3D collision detection? I believe I've heard Bullet has a pretty good 3D collision detection that can be used without the physics engine. I'd like to hear if people have any experiences on Bullet or other libraries for 3D collision detection specifically. |
18 | What's the fastest collision detection (Game Maker) I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10). Each step, I want the cells to check around itself for obj A to see if any obj A is "touching" it, (has a distance less than 10 from the cell). However, since I have so many obj Cell and so many obj A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj A number of obj Cell) In obj Cell (with obj A) if distance to object(other) lt 10 do stuff Is there any possible way to make this faster? |
18 | AABB test does not consistently detect edge to edge contact when bounds are very different in size My function compares two AABBs for collision detection, and when they are around the same size it works fine, but I noticed that if I greatly decreased the size of one of them (or augmented the size of the other), then the collision wouldn't be detected correctly I would have to have them intersect for a collision to be registered, rather than having it register when they are at least in direct contact, which is the intended behavior. Below is my code local function DetectCollision(a, b) AABB to AABB local collisionX (a.Position.X a.Size.X) gt b.Position.X and (b.Position.X b.Size.X) gt a.Position.X local collisionY (a.Position.Y a.Size.Y) gt b.Position.Y and (b.Position.Y b.Size.Y) gt a.Position.Y local collisionZ (a.Position.Z a.Size.Z) gt b.Position.Z and (b.Position.Z b.Size.Z) gt a.Position.Z return collisionX and collisionY and collisionZ end To be more specific, the issues start to occur when I cut the size of one of the AABBs in half. For instance, if I had two cubes where one's size is 12 on all axes and the other is 6 on all axes, then the collision will not register. Upon debugging, I noticed that only one of the collision bools will become false. This seems to depend on what axis the smaller bounding box moves from in relation to the bigger one, so if I moved the smaller AABB away from the bigger one on the y axis, then collisionY will be false. |
18 | One SKSpriteNode with multiple PhysicsBodies? I am making a game similar to Lunar Lander, when you land with your ship on different objects, etc... The issue I am having is that I have a Player SKSpriteNode (my Ship) with a slightly complex collision system (bottom of the ship has different CategoryBitMask from other sides, etc.) and when I apply PhysicsBody(bodies physicsBodiesArray ) I cannot control CategoryBitMask for each element of the physicsBodiesArray ... Because main PhysicsBody is applied to the Player it overrides all other Categories and such. Here is my "createPlayer" function Creating the player player SKSpriteNode(imageNamed "Bottle 02") player.size CGSize(width 130, height 200) player.position CGPoint(x 0, y 0 player.frame.height 2) Creating 2 collision objects and placing them var playerColTop SKSpriteNode() var playerColBottom SKSpriteNode() playerColTop SKSpriteNode(imageNamed "test top") playerColBottom SKSpriteNode(imageNamed "test bottom") playerColTop.position CGPoint(x 0.5, y 0) playerColBottom.position CGPoint(x 0.5, y 0 playerColTop.frame.height 2 playerColBottom.frame.height 2) Creating PhysicsBodies for the Array and assigning CategoryBitMasks let playerColTopPhys SKPhysicsBody(texture playerColTop.texture!, size playerColTop.size) let playerColBottomPhys SKPhysicsBody(texture playerColBottom.texture!, size playerColBottom.size) playerColTopPhys.categoryBitMask PhysicsParams.Player playerColTopPhys.collisionBitMask PhysicsParams.Ground PhysicsParams.Walls playerColTopPhys.contactTestBitMask PhysicsParams.Ground PhysicsParams.Walls playerColBottomPhys.categoryBitMask PhysicsParams.PlayerScore playerColBottomPhys.collisionBitMask PhysicsParams.Ground PhysicsParams.Walls playerColBottomPhys.contactTestBitMask PhysicsParams.Ground PhysicsParams.Walls Adding my PhysicsBodies and setting up the Player player.physicsBody SKPhysicsBody.init(bodies playerColTopPhys, playerColBottomPhys ) player.physicsBody?.categoryBitMask PhysicsParams.Player player.physicsBody?.collisionBitMask PhysicsParams.Ground PhysicsParams.Walls player.physicsBody?.contactTestBitMask PhysicsParams.Ground PhysicsParams.Walls player.physicsBody?.restitution 0 player.physicsBody?.friction 1 player.physicsBody?.mass 5 player.physicsBody?.affectedByGravity false player.physicsBody?.isDynamic false self.addChild(player) Thanks in advance! |
18 | Game Maker 8.0 Can I simulate any collision event within the step event of an object including the "other" reference? Let's say I have two objects. One is "obj wall" and the other is "obj player". For the sake of argument, let us assume that I cannot just add a collision event to obj wall (I truly cannot due to limitations embedded within the nature of the project itself). Is there a function or block that allows one to write a collision event within obj wall's step event? I know there are various collision detection functions, but what I need is one that acts identically to the collision event and allows me to access the "other" property. If this is not possible, are there any suitable alternatives (such as a function that detects collision and returns the instance id of an object colliding the wall)? My primary issue here is that I want to be able to use collision in one instance of an object without having to have the collision event added. I'd prefer it to be as close as possible to the collision event so as to avoid unnecessary extra checks. |
18 | How do I determine wall direction, with information of normal and incoming direction? What is formula and theorys used to determine wall direction, with only knowing the normal of the wall and the direction of the incoming object? This answer has already stated a formula, but I don't know where it came from, and I am in need of understanding. |
18 | Collision detection in multiplayer games This a followup to my previous question How to implement physics and AoE spells in an MMO game?. There, we concluded that all physics have to be done on the server, and that I should use cylinders for calculations. Now, how can I check for collision detection on a ground to player basis on the server? It's fairly easy if the ground is a flat space, I just check if the player's z coordinate is lower than some value and voila, but, what if the map ground itself is a model? How do I know where hills are on the server side? How do I know when object collisions happen? I'm using node.js and socket.io. |
18 | What type of Collider should I add to a LineRenderer? I am currently building a game where I need to generate some wires (as B zier curves) using LineRenderer. After changing the width of each line lineRenderer.SetWidth (0.15f, 0.15f) I am attaching an EdgeCollider2D to the same game object (specifying the same points used in generating the B zier curve). This seems to work. However, I would like to be able to know if the Mouse Pointer is at any time over the EdgeCollider2D (something similar to the popular Fruit Ninja game). I'm using Raycast as follows void CastRay() Ray ray Camera.main.ScreenPointToRay (Input.mousePosition) RaycastHit2D hit Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity) if (hit) Debug.Log (hit.collider.gameObject.name) I'm calling the CastRay method inside the Update method. Because EdgeCollider2D does not have width (as expected), the log message is never produced. Do I need to use a different type of Collider? Do I need to call CastRay somewhere else? |
18 | Collision resolution when moving in two directions I am making a bomberman clone and I'm having problems regarding moving on both x and y axis (pressing down left, down right, up left). Here is a video to demonstrate the problem. I use Tiled for the map. Below is the code private void checkCollision(float delta) player.getVelocity().scl(delta) dont mind Vector2 position player.getPosition() if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles To reproduce the problem shown in the video Try to collide (coming from up) with one of the blocks that is not on the sides, press both down and left. Try again but press down and right. For the third one, make sure you are colliding with the top wall by pressing up then press left (both are pressed). It can also be done on the bottom wall by pressing down and left. |
18 | Am I implimenting a sweep and prune broadphase correctly? The code that I am using is std vector lt PhysicsBody gt physicsChildren containing all objects ... std sort(physicsChildren.begin(), physicsChildren.end(), sortByLeft) std vector lt PhysicsBody gt activeList unsigned int one unsigned int two for(one 0 one lt physicsChildren.size() one) activeList.push back(physicsChildren one ) for(two 0 two lt activeList.size() two) if (physicsChildren one gt m position.x physicsChildren one gt m radius gt activeList two gt m position.x activeList two gt m radius) CheckIntersectionBetween(physicsChildren one , activeList two ) else activeList.pop back() I think something is wrong because for 800 objects 309169 calls to CheckIntersectionBetween. A bruteforce would use 640000 calls, I didn't think this was much improvement (considering only objects close in the x axis should test). I wrote the code from reading Jitter Physics article about SAP Create a new temporary list called activeList . You begin on the left of your axisList, adding the first item to the activeList. Now you have a look at the next item in the axisList and compare it with all items currently in the activeList (at the moment just one) If the new item s left is greater then the current activeList item right, then remove the activeList item from the activeList otherwise report a possible collision between the new axisList item and the current activeList item. Add the new item itself to the activeList and continue with the next item in the axisList. What have I done wrong? |
18 | What are the technologies that makes physics engines so good for raycasting? again. This question is strictly related to this one so, what is the technology that makes physics engines suitable for raycasting? It is a particular data structure? Has it to do with the engine's internal representation of the objects? If so, how do they represent objects so to be able to make polygon precise raycasting? Do they hold the whole information about a mesh? |
18 | player teleporting into other levels So I basically want to load another map once the player collides with a object, specifically a quot Portal quot in my game. Which is really making the player move onto other levels. I don't want to jumble up my code with a bunch of function like quot go to level 9 quot or something so I'm planning to use a list or dictionary or something. So how to those game devs out there do that? Code for main.py is here https pastebin.com rpddq1MP. The part with the portal stuff, walls and a few others for tile object in self.map.tmxdata.objects obj center vec(tile object.x tile object.width 2, tile object.y tile object.height 2) if tile object.name 'player' self.player Player(self, obj center.x, obj center.y) if tile object.name 'zombie' Mob(self, obj center.x, obj center.y) if tile object.name ' ' Obstacle(self, tile object.x, tile object.y, tile object.width, tile object.height) if tile object.name in 'health', 'shotgun' Item(self, obj center, tile object.name) if tile object.name 'portal' self.map TiledMap(path.join(self.map folder, tile object.type)) how do you do it? I'm currently using Tiled and pygame so I'm also using pytmx. Edit When I run the code, it just gives me an error about my other file, tilemap.py. Error File quot D coding my coding stuff python games pygames little rpg tilemap.py quot , line 49, in apply return entity.rect.move(self.camera.topleft) AttributeError 'TiledMap' object has no attribute 'rect' Tilemap.py import pygame as pg import pytmx from settings import def collide hit rect(one, two) return one.hit rect.colliderect(two.rect) class Map def init (self, filename) self.data with open(filename, 'rt') as f for line in f self.data.append(line.strip()) self.tilewidth len(self.data 0 ) self.tileheight len(self.data) self.width self.tilewidth TILESIZE self.height self.tileheight TILESIZE class TiledMap def init (self, filename) tm pytmx.load pygame(filename, pixelalpha True) self.width tm.width tm.tilewidth self.height tm.height tm.tileheight self.tmxdata tm def render(self, surface) ti self.tmxdata.get tile image by gid for layer in self.tmxdata.visible layers if isinstance(layer, pytmx.TiledTileLayer) for x, y, gid, in layer tile ti(gid) if tile surface.blit(tile, (x self.tmxdata.tilewidth, y self.tmxdata.tileheight)) def make map(self) temp surface pg.Surface((self.width, self.height)) self.render(temp surface) return temp surface class Camera def init (self, width, height) self.camera pg.Rect(0, 0, width, height) self.width width self.height height def apply(self, entity) return entity.rect.move(self.camera.topleft) def apply rect(self, rect) return rect.move(self.camera.topleft) def update(self, target) x target.rect.centerx int(WIDTH 2) y target.rect.centery int(HEIGHT 2) limit scrolling to map size x min(0, x) left y min(0, y) top x max( (self.width WIDTH), x) right y max( (self.height HEIGHT), y) bottom self.camera pg.Rect(x, y, self.width, self.height) |
18 | Simple Bounding Box Multiple Collision problem I'm making my first game, and in it I use a moving ball to hit static blocks (kinda like breakout). Basically, I loop through all of the static blocks on the screen each frame, update the position of the ball based on its velocity, and if it collides with a block, the ball will bounce back off of the block. If the ball hits one block exactly, then there is no problem whatsoever. But if the ball happens to hit two blocks at the same time (that is, it hits in between both blocks), it passes right through both of them no deflection whatsoever. (I know the looping is inefficient and I'm looking to correct that later, but if it has to do with the problem, I just hope someone can point to me why it is that the collision resolution fails when two similar objects are hit at once.) |
18 | HTML5 platformer collision detection problem I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code. I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here Platform engine test. Arrow keys move and z run, x jump, c shoot. Try to jump into the first pit and slide on the wall. Here's the collision detection code function checkCollisions(a, b) if ((a.x gt b.x b.width) (a.x a.width lt b.x) (a.y gt b.y b.height) (a.y a.height lt b.y)) return false else handleCollisions(a, b) return true function handleCollisions(a, b) var a top a.y, a bottom a.y a.height, a left a.x, a right a.x a.width, b top b.y, b bottom b.y b.height, b left b.x, b right b.x b.width if (a bottom a.vy gt b top amp amp distanceBetween(a bottom, b top) a.vy lt distanceBetween(a bottom, b bottom)) a.topCollision true a.y b.y a.height 2 a.vy 0 a.canJump true else if (a top a.vy lt b bottom amp amp distanceBetween(a top, b bottom) a.vy lt distanceBetween(a top, b top)) a.bottomCollision true a.y b.y b.height a.vy 0 else if (a right a.vx gt b left amp amp distanceBetween(a right, b left) lt distanceBetween(a right, b right)) a.rightCollision true a.x b.x a.width 3 a.vx 0 else if (a left a.vx lt b right amp amp distanceBetween(a left, b right) lt distanceBetween(a left, b left)) a.leftCollision true a.x b.x b.width 3 a.vx 0 function distanceBetween(a, b) return Math.abs(b a) |
18 | Box collisions between vehicles in traffic pattern I'm working on a traffic simulator. Right now, I have ways to manage 4 way stop intersections and a solution for efficiently determining which vehicles are colliding with one another. All vehicles operate independently of each other and will overlap ignore any vehicles they pass. I'm looking to build a way to resolve collisions between vehicles such that a Vehicle will follow the Vehicle in front of it. If a Vehicle stops at an intersection, any Vehicles that follow thereafter should stop and wait as well. Below are the relevant components I already implemented TileGrid containing road segments. TravelGraph graph of waypoints for Vehicles to travel along the TileGrid. CollisionTracker for efficiently determining which vehicles are colliding, i.e. O(1) lookup for get collisions( lt vehicle id gt ) gt List lt vehicle ids gt Intersection for determining which vehicles are waiting at an intersection and determining which Vehicles may pass through it. The only seemingly viable algorithm right now is Calculate velocities and position of all vehicles after tick Determine which vehicles are in a collision Determine which vehicles are in a "collision group" (e.g. if A collides with B, collides with C, then (A, B, C) are in a group) Determine the order of the vehicles in each group based on their velocities (e.g. if A, B, and C are moving to the right and C is the rightmost, followed by B, followed by A, then the order is C, B, A ). Recalculate the positions of all vehicles, in order from front to back (e.g. C, B, A) such that they reside adjacent to, but not touching the Vehicle in front of them. Problems with this solution This requires a lot of recalculations. If there's a line of n vehicles waiting on a light, I'd effectively compute 2 n positions per tick in addition to all other overhead for establishing groups, order, etc. If the vehicles are following each other around a turn, the logic for finding the "vehicle order" becomes more complex, adding on to the computations per tick. Ideally moving the vehicles would require n calculations per tick. I'm open to any all suggestions here. I've tried building my code as modular as possible, so I'll happily rewrite large parts of it if there's a better architecture to solve this problem. Below is the visual representation of the TileGrid (black), TileGraph (purple), and Vehicles (circles). |
18 | Gravity and collision detection interfering with player movement I am attempting to implement collision detection for a 2d sidescroller game and I'm having trouble keeping gravity from interfering with player movement. Every frame I get and handle input, creating values for a point that represents the players movement vector. I then add gravity to the vector and check for collisions. This is the way AI will be handled as well. The problem I'm having is when the player is on a floor tile, even if the input says to walk horizontally, after I add gravity to the move vector, collision detection returns a collision so the movement is completely negated. I know i can test which a is is the problem, negate that and move the player but then if I change the players movement vector inside collision testing, wouldn't I have to cull for collisions again based off the new move vector? I don't know if this has to do with input handling or collision testing. So how should I go about adding gravity to the players movement? |
18 | Ways to define a curve I'm trying to give shapes in my physics engine roundness curvature. I am aware of various methods for mathematically defining curves such as bezier cruves, ellipses, etc. However I am not sure which methods would be most appropriate for use in my physics engine, because speed, feasibility of construction, and flexibility of each method must be considered. I want a system in which a user can easily form fairly complex curves, but still make the intersection calculations simple and fast. My physics engine is also purely continuous, which means I must be able to calculate the time in which curves will collide with other curves and lines based on a constant linear angular velocity. What techniques are there for mathematically defining a 2D curve? What are the advantages disatvantages of each in terms of speed, flexibility, and simplicity of construction? Is the technique feasible for an engine where predictability of shape intersection is crucial? |
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 | Collision detection in Arkanoid like game at intersections I'm creating an Arkanoid like game from scratch. I have no (formal or informal) education of any kind in game development, so I kinda made up things as I went regarding collision detection based on personal ideas of "how it probably works". I approximate the ball as a point and ignore its thickness, which is small anyway. I compensate for this visually by very slightly making all objects smaller than they are. I don't "detect" collision, but anticipate it and change the outcome of the next frame. For example The ball is currently in position A, and it "wants" to go to E (red line). But I calculate all intersections with all segments which make up the bricks B, C, D. The closest one to starting point (A) is B, so I choose B as the "real" intersection. I destroy the brick this segment belongs to. Now I check how would the ball proceed if it would start at B, with its vector flipped horizontally (because I determine that the segment it hit was horizontal). This is the blue line. Again, from F and G, I pick F. I destroy the brick this segment belongs to. Lastly, the orange line doesn't intersect, so I determine that the bottom of the orange line is where I should place the ball in the next frame. This worked fine and I was satisfied with it, until I started nailing the edge case of the ball hitting the T intersection, where it all goes bananas. What should happen here is that the ball bounces to the left and destroys either of the bricks. But what can happen is that my algorithms decides to choose the middle vertical segment (connecting boxes 1 and 2) as the collision point, either belonging to the 1st or 2nd box. I thought of ignoring the edges of the segments, but then the ball would pass right through the T intersection in this scenario, because it would also ignore what it's supposed to hit. You can see it in action here (around after 00 07 mark) https www.mp4upload.com p6966u6kuzad What are common techniques for handling this case? Even if I introduce the width to the ball, it could still hit the exact T intersection at the tangent, so the problem would remain. Requested to post code. Here's the main bit. Please note that I'm not expecting you to (or looking for) debugging the application. I'm more asking about how are these things even handled in general. export function bounceBall( ball Point, vx number, vy number, obstacles Obstacle , ) const projectedNextPoint ball.clone().translate(vx, vy) const movement new Segment(ball, projectedNextPoint) const touchedObstacles Obstacle let loop 10 let hasCollision false do hasCollision false if (loop lt 0) throw new Error('oops') If in the previous loop the ball just grazed the surface if (movement.isZeroLength()) break const collisions Collision for (const obstacle of obstacles) const collision getIntersectionOfSegmentAndObstacle ClosestToStartExcludingStart(movement, obstacle) if (collision ! null) collisions.push(collision) const collision getClosestCollisionExcludingSelf(movement.start, collisions) We don't count a collision if it's the starting point. If we did, grazing a surface would turn into an infinite loop. if (collision null Point.AreEqual(collision.point, movement.start)) hasCollision false else hasCollision true touchedObstacles.push(collision.obstacle) if (hasCollision) movement.setStart(collision!.point) if (collision!.segment.isVertical()) movement.mirrorVerticallyWrtStart() vx vx if (collision!.segment.isHorizontal()) movement.mirrorHorizontallyWrtStart() vy vy while (hasCollision) return touchedObstacles, vx, vy, newBall movement.end, |
18 | Tiled height level collision I have created the below tilemap in tiled and I am wondering about a good approach to "separate" these two different heights in the map. I would like to keep it tile based, so adding a object layer for collision detection is a no for me. I would like the player to move from the low ground to high ground using the ladder. But as you can see, two walkable tiled adjacent to each other should not be "connected" since they are on different heights. Since I can only add properties to the tile in the sheet and not on the map itself afaik, I cannot mark the heights on my map. So I guess I have to work with different layers for each height. Check if the layer the player currently on has a tile or something, if that is even possible. The reason I do not want to use a object layer is simple. My creatures move from tile to tile and I just want to check if that tile is walkable and on the same height level. No need to test vs a rectangle or polygonal object. What I am actually looking for is having properties per coordinate. This would make it a lot easier (pseudo code) tileMap x y .floorCount tileMap x y .walkable instead of map.getLayer(player.currentLayer).layerMap x y .tileExists map.getLayer(player.currentLayer).layerMap x y .walkable I simply cannot add properties to a "global" tile (tiled seems to only allow me to add properties to the tile on the sheet which is carried over to every usage of it. This image uses that same corner tile as in the above image, only this time the player is allowed to cross it, or perhaps hop over it. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.