At same positioned game objects collision detection In my game, I am creating two game objects at same position using Instantiate statement. Each generated object has box collider attached. So I want to detect collision between them so I write following code. void OnCollisionStay(Collision collisionInfo) print("on collision stay") But this statement not called. I generate two object using following code. BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero) BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero) I need help in collision detection. I already post question in unity forum but I didn't get any reply from there.


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 ?


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?


Point vs Convex Hull I'm trying to implement a simple collision response to a point intersecting a convex hull. So far I can detect if the point is inside the hull. But now I want a collision response that translates and rotates the hull away from the point so it no longer intersects. I'd like the simplest algorithm possible, I don't want to implement a physics engine or rigid bodies. Can someone point me in the right direction?


Color Based Collision Javascript (Cocos2d js) I'm looking to make an isometric game so my partner designed the isometric map (jpg image) along with the map objects (png) on Adobe Illustrator. The thing is I would like to set the player path based on color, for example if the terrain is white the player can go through, if it's black then the player is not allowed to pass. Is this a viable method to do this or are there better methods? Also I'm using Cocos2D js so my coding is JavaScript I would appreciate any suggestions.


How to prevent a sprite to move in an angle that will lead to collision I have two sprites that can move in any angle. The sprites are rectangular. I created bounding boxes for both the sprites. These boxes rotate whenever the sprite rotates. They always surround the sprite and only the sprite. (Exact fit). I have succesfully implemented collision detection for the two bounding boxes. I did this by checking wether box1 contains any of the vertices of the box2, and the opposite. (I know this way is not perfect, since it is possible for two rectangles to intersect without having each other's vertices inside themselves, but for my needs it's good enough). So now I know when the two sprites collide. But I have a problem with reacting when the two sprites collide. When these sprites collide, I want to prevent them from overlapping each other (any more than a few pixels). In other words, upon collision, I want to allow the sprite to move only in a direction where it won't go deeper into the other sprite. As I said, each sprite can move freely in any angle (the game is for two players, each controls a sprite). EDIT To word it differently Upon collision of two sprites, I need to find out the range of angles a sprite can move, that will allow it to to move out of the collision this is so I can prevent the user from moving the sprite in any other angle, upon collision. How can I do that? Thank you for your help


Where should I save game object's attributes (hp, score) in Swift? Scenario I have a game with several game objects on screen. Each can have different score and hitpoints. When I use collision detection for cannonball vs. ship (example) I need to know which ship is hit and how much hitpoints it has. Problem I had several approaches from extending SKSpriteNode or SKPhysicsBody but all failed. SKSpriteNode doesn't work, because Swifts collision detection only returns physicsBody and since you can't extend physicsBody, it didn't work to save there ships attributes as well. Question What would be a good approach to save such data to my game objects? I do not need code because I think I can write it myself but I would be happy to read a good suggestion. But if you have already some code written and a good solution for this problem, I would not be angry to read it )


Determine if Plane is seen by Camera If I have an arbitrary plane (center and normal) or a quad (center, normal and width and height) and a camera (frustum, projection amp view matrix, etc). Then how would I go about calculating if the plane quad is visible to the camera? Additionally how would I calculate to check if it's the front or the back of the plane quad that is visible to the camera? My first idea was to do some ray vs plane intersection, but then I realized that it of course wan't going to work! bool plane visible false const float denom plane normal.dot(camera.getLook()) if (abs(denom) gt 0.0001f) const float t (plane position camera.getPosition()).dot(plane normal) denom plane visible (t gt 0.0f) Using the dot product of the plane quads normal and the camera's look direction. Will give wrong results! For instance, use the following image as an example! A dot product will tell me that I'm looking at the face that's facing outwards of the frustum. Though the face that I'm actually looking on is face facing inwards the frustum towards the camera!


How to make a cylindrical collider for a cylindrical mesh in UE4 When I am importing Axis Alligend cylindrical mesh in UE4 here is what I get as an automatically generated collider But if I rotate the mesh in Maya and again exprot FBX to improt in UE4 here is what I get As you can see the object is the same but the collider is much worse. How can I make the same callider in spite of the orientation of the cylinderical mesh? BTW if I remove collider and do auto convex collider I get this Which is very good but the problem is that I want it to be generate from the beginning and not later when I edit the mesh collider. How can I achieve that?


How do I efficiently perform collision detection on an NxN rectangle grid? I have a simple level that is constructed from an NxN rectangle grid. Some of the rectangles are walls, and some of them are the path. The player is allowed to move only on the path they are on and also the path rectangles on the grid. So I have two kinds of rectangles in the grid "path" "wall" The player is a sprite above the grid. I want to efficiently find if the player is colliding with the wall. I want to loop through the rectangles, to see if they intersect. What is the best method?


Libgdx detect when player is outside of screen Im trying to learn libGDX (coming from XNA MonoDevelop), and I'm making a super simple test game to get to know it better. I was wondering how to detect if the player sprite is outside of the screen and make it so it is impossible to go outside of the screen edges. In XNA you could do something like this Prevent player from moving off the left edge of the screen if (player.Position.X lt 0) player.Position new Vector2(0, player.Position.Y) How is this achieved in libgdx? I think it's the Stage that handles the 2D viewport in libgdx? This is my code so far private Texture texture private SpriteBatch batch private Sprite sprite Override public void create () float w Gdx.graphics.getWidth() float h Gdx.graphics.getHeight() batch new SpriteBatch() texture new Texture(Gdx.files.internal("player.png")) sprite new Sprite(texture) sprite.setPosition(w 2 sprite.getWidth() 2, h 2 sprite.getHeight() 2) Override public void render () Gdx.gl.glClearColor(1, 1, 1, 1) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL LEFT)) sprite.translateX( 1f) else sprite.translateX( 10.0f) if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) if(Gdx.input.isKeyPressed(Input.Keys.CONTROL LEFT)) sprite.translateX(1f) else sprite.translateX(10f) batch.begin() sprite.draw(batch) batch.end()


How do I determine which voxels to test for collision against the player? I've implemented Minkowski subtraction to test whether (and where) two AABBs collide, independent of framerate time step, in my Minecraft like game. But since there may be tens of thousands of voxels, I'm realizing I can't just test everyone of them. Is there an alternative to just scanning for nearby voxels? I worry that if I just do collision for voxels within a fixed range, then I've undone the framerate independence that I had sought.


2D platformer How to avoid "bouncing descend" when walking down slopes? I've been working on implementing slope collision by SAT(Separating Axis Theorem). And then I have a trouble. When my character walks down slope, it moves like a bouncing ball The slope has 3 sprites (45 ) Here is my current code with JavaScript slopes.forEach((slope) gt Minimum Translation Vector let mtv character.collidesWith(slope) if(mtv.overlap ! 0) character.velocityY 0 character.positionY mtv.overlap ) It works good when moving up, but bouncing when down, I have no idea how to keep the character stay on slope when walking down. Please, any help would be appreciated.


Calculating normal vector on a 2d pixelated map I want to know an efficient way to get the normal of the surface of a 2d map. suppose an object hit the map, i want the object to bounce accordingly. The problem is, the "bounding box" of said object is several pixels in size and the map has many curves. I thought about getting the pixels that collides with the object (don't ask me how) and calculating it's mean, and having the normal to be the line between said pixel and the center of the object for those familiar with worms, I want to do the same when a grenade hits the map and bounces back EDIT I'm not looking for a 100 accurate formula, I want it to be efficient and believable enough


Collision representation in game overworlds I'm implementing a 2D overworld where one can walk through an area that is not tile based. I was wondering the best way to implement collisions. In the past when I've done similar things, I've used one image (or set of images) to show an elaborately drawn world and then a second binary image that does nothing but differentiate "wall" and "not wall". Then, I'd use the first for all drawing to the screen, but the second for collision detection. Having another image of the same size to represent collisions seems like lots of overhead. Is there a better way to handle this? (I'm currently using C with SDL, although I'm more interested in general concepts)


Hit detection for partially covered object? Say you have a character standing behind cover such that some of its body parts like a shoe or a palm is still outside the cover. An explosion takes place close to the cover . In real life this would mean the player getting damage in his arm or whichever body part was outside the cover. How would you simulate this kind of hit detection efficiently in a game ? An approximation would be to line trace from center of the explosion to each bone in the character mesh. But it might still not be accurate enough for larger bones , would be performance intensive and would not work for objects which are not skeletal meshes.


Collision detection between a sprite and rectangle in canvas I'm building a Javascript canvas game which is essentially a platformer. I have the player all set up and he's running, jumping and falling, but I'm having trouble with the collision detection between the player and blocks (the blocks will essentially be the platforms that the player moves on). The blocks are stored in an array like this var blockList 50, 400, 100, 100 And drawn to the canvas using this this.draw function() c.fillRect(blockList 0 0 , blockList 0 1 , 100, 100) I'm checking for collisions using something along these lines in the player object this.update function() Check for collitions with blocks for(var i 0 i lt blockList.length i ) if((player.xpos 34) gt blockList i 0 amp amp player.ypos gt blockList i 1 ) player.xpos blockList i 0 28 return false Other code to move the player based on keyboard input etc The idea is if the player will collide with a block in the next game update (the game uses a main loop running at 60Htz), the function will return false and exit, thus meaning the player won't move. Unfortunately, that only works when the player hits the left side of the block, and I can't work out how to make it so the player stops if it hits any side of the block. I have the properties player.xpos and player.ypos to help here.


Efficient collision detection tile based HTML5 Javascript game I'm building a basic RPG game and I'm looking at collisions pickups etc now. It's tile based and I'm using HTML5 and Javascript. I use a 2D array to create my tilemap. I'm currently using a switch statement for whatever key has been pressed to move the player. I have if statements to stop the player going off the edge of the map and viewport. If the player is about to land on a tile with tileID 3 then the player stops. Here is the statement canvas.addEventListener('keydown', function(e) console.log(e) var key null switch (e.which) case 37 Left if (playerX gt 0) playerX if(board playerX playerY 3) playerX break case 38 Up if (playerY gt 0) playerY if(board playerX playerY 3) playerY break case 39 Right if (playerX lt worldWidth) playerX if(board playerX playerY 3) playerX break case 40 Down if (playerY lt worldHeight) playerY if(board playerX playerY 3) playerY break viewX playerX Math.floor(0.5 viewWidth) if (viewX lt 0) viewX 0 if (viewX viewWidth gt worldWidth) viewX worldWidth viewWidth viewY playerY Math.floor(0.5 viewHeight) if (viewY lt 0) viewY 0 if (viewY viewHeight gt worldHeight) viewY worldHeight viewHeight , false) Is there a more efficient way of handling collisions, than loads of if statements for each key? The reason I ask is because I plan on having many items that the player will need to be able to pickup or not walk through like walls cliffs etc.


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.


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.


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


Bump and push entities without a physics engine I have seen on many games the ability to push entities around and bump into enemies characters. What is this called? I have implemented Matterjs to accomplish this with Pixijs but it seems overkill when I just need the ability to bump and push. I'm not really interested in an accurate physics model, just collision enough to allow the character to interact with the environment. I can't seem to find out what this is called. My idea is to have all entities defined by a circle collision boundary, and move away from the character based on primitive collision detection and a tangent force calculation to displace.


Non rectangular collision detection in Python and Pygame I am programming a ray tracer in python, and I have gotten as far as making a character that can move across a 2d plane and change direction of movement when needed. The problem is this I want to be able to use an image with transparency as the maze that the player travels through, and use transparent parts as parts that aren't walls, where as every thing else is a wall. The way I am using collision detection is by using the quot pygame.sprite.spritecollide quot method, which takes in a Sprite, and a Sprite Group. So I first add the map sprite object to the group, and then in the main while loop, it checks for collision. Here is a small snippet of what that might look like map Map( quot map1.png quot ) quot Map quot class is regular sprite class but with quot image quot and quot rect quot group pygame.sprite.Group() group.add(map) inbetween stuff would be here while loop running True while running event handling stuff would be here if pygame.sprite.spritecollide(player, group, False) print True screen drawing routines would be here As I mentioned, the image has transparency. But never the less, the image rect sticks to the non transparency position that it was, so i have to move the player off screen to get the console to stop saying quot True quot . So what I ask, is there a way that I can check for sprite collision but with transparency?


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!


Libgdx Check collisions in Stage among actors My goal is to check collisions among the actors that are in the Stage. My question is is it necessary to maintain a list for each type of actor I have? Doing that I get 3 problems, 2 bad design problems and 1 exception. Design problems I don't like The Actors used by the player add bullets (another Actor) to the stage. I need to pass my Stage to these Actors as argument in order to add a bullet to the list of bullets, that is held by the Stage. Each time I need to add an Actor to the Stage, I have to perform 2 add operations, one in the list and one directly to the Stage. If I check collisions iterating over the lists and I find out that an enemy (another actor) is dead, I need to remove the enemy both from the stage and from the list, but I can't remove it from the list because I get "Concurrent modification exception". Is there some common design technique to handle this stuff?


removing box2d objects before collision occurs I am having a problem with a collision detection between the character and items, both created as box2d objects. What I am trying to do is to delete the item or remove item from the collision method before character hits item and bounces away. Thus, I want to detect when the item and character collided to gain item effects. Current sources are as below mWorld.setContactListener( new ContactListener() Override public void endContact(Contact contact) Override public void beginContact(Contact contact) Body bodyA contact.getFixtureA().getBody() Body bodyB contact.getFixtureB().getBody() Box2DUserData dataA (Box2DUserData) bodyA.getUserData() Box2DUserData dataB (Box2DUserData) bodyB.getUserData() if( dataA.id Box2DUserData.ID ITEM ) mWorld.destroyBody(bodyA) bodyA.setTransform(new Vector2( 0, 0 ), 0 ) bodyA.setActive(false ) else if( dataB.id Box2DUserData.ID ITEM ) bodyB.getWorld().destroyBody(bodyB) bodyB.setTransform(new Vector2( 0, 0 ), 0 ) mWorld.destroyBody(bodyB) bodyB.setActive(false ) ) This source works okay, but the bodies are removed after collision detection. So I can get the character walk through items, after the character bumped in item and stopped for a frame or so. I am not sure if I am supposed to use World.setContactListener or another method, it would be grateful if someone could give me the right method or another way to detect collision and the way to remove body from collision method before it actually collides. Thanks


Raycasting Collision Detection I need to check for collisions when firing a bullet, but I have a few questions first. My game is 2D and tile based, it also uses the XNA framework. From what I've read raycasting or continuous collision detection is the way to go for high speed bullets. XNA has a method called Ray.Intersects which takes a bounding box, does this mean that I should be starting at a point and looping through all the tiles in a line to see which tile intersects like this? Now that example required 10 checks and now I have the information I need to know where the collision is exactly, but wait what if a person jumps in line of the ray? Well now I need to be performing these checks every frame in order to determine if a player comes in line. Assuming my game has a solid 60 FPS I'm now up to 60 checks every second or 10 checks a frame. Maybe I've shot my weapon 5 times and the wall is 50 blocks away, that would be a lot of checks. So if you couldn't figure out what I'm getting at here these are my questions. In order to preform raycast collisions do I start at a point (barrel of weapon) and loop through all the tiles asking "does the ray hit this tile?" until I've hit something (a wall)? How do I optimize it or does it even need optimizing? Remember the system needs to... be able to obtain all the necessary information such as where does the collision take place exactly? account for players or obstructions getting in the path of the ray.


CCD in C Console application I am writing a game in a c console application. I would like to detect whether or not there is a collision between two objects, and displace them accordingly. All sprites are simply strings drawn on screen (Ex. a sprite with x 5, y 5, width 3, height 3 and the image "XXXXOXXXX" would create a 3 by 3 box of X's with a O in the middle). All objects have a x, y, length, and width which can aid in looking for potential collisions however I would like to look at the actual string for finer collision detection. I am relatively new to the concept of continuous collision detection and I am having trouble finding the answer via Google. Does anybody know how I would go about doing this? Thanks in advance.


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


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 ?


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?


Different collision effects on different objects I'm a beginner to Corona and game development. I am using a variety of objects in my game. On collision, they all perform the same function. I want them to do different things, and also want some objects to only collide with certain other objects. How would I go about doing this?


How to properly handle attacks in an 2D Platformer? I am building an 2D Engine in JavaScript and if my actor attacks an enemy, a hitbox appears for a certain amount of time and then disappears. If the target keeps standing inside of the hitbox he gets drained down for each frame. So for example if the hitbox does 3 points damage and the target only has 9 HP he will be dead after 3 frames. That's too fast. I've come up with two solutions, both of them are not ideal Set the enemy as unattackable for a certain amount of time after each hit. Save an reference to the enemy that gets deleted after the hitbox disappears. My explanation is pretty bad but posting my code would be worse since it's way too much.


Whats the physics behind the doodle jump game? I'd like to know how we can achieve the doodle jump type physics using andengine. I mean the character is not colliding with the ground blocks when he moves upwards but will collide when he came downwards and will make a jump from their. Can it be achieved using the collision filter? If yes how? Is it possible to enable and disable collision filter for particular bodies dynamically?


Deactivate keyboard input on collision I'm creating an online canvas game with a tank as player object. Now I have several structures in my canvas, that shouldn't be able to be overdriven by the tank... My solution is to detect the collision like that if(hero.x gt reactor i 'x' 32 amp amp hero.x lt reactor i 'x' 32 amp amp hero.y gt reactor i 'y' 32 amp amp hero.y lt reactor i 'y' ) collidetop true if(hero.x gt reactor i 'x' 32 amp amp hero.x lt reactor i 'x' 32 amp amp hero.y gt reactor i 'y' amp amp hero.y lt reactor i 'y' 32) collidebottom true if(hero.x gt reactor i 'x' 32 amp amp hero.x lt reactor i 'x' amp amp hero.y gt reactor i 'y' 32 amp amp hero.y lt reactor i 'y' 32) collideleft true if(hero.x gt reactor i 'x' amp amp hero.x lt reactor i 'x' 32 amp amp hero.y gt reactor i 'y' 32 amp amp hero.y lt reactor i 'y' 32) collideright true The hero object is the tank, hero.x the x coordinate, and so on... Now I'd like to deactivate the keyboard input for the direction key, if the objects collide... For this reason I have the variables wok, aok, sok and dok they all contain booleans. If wok false, then the key "w" is deactivated... I've connected the collide variables to the keyboard inputs if(collidetop true) sok false if(collidetop false) sok true if(collidebottom true) wok false if(collidebottom false) wok true if(collideright true) aok false if(collideright false) aok true if(collideleft true) dok false if(collideleft false) dok true My problem is if the tank doesn't collide the other object any more, the keys stay blocked... Could you help me with that?


Why doesn't Unity's OnCollisionEnter give me surface normals, and what's the most reliable way to get them? Unity's on collision event gives you a Collision object that gives you some information about the collision that happened (including a list of ContactPoints with hit normals). But what you don't get is surface normals for the collider that you hit. Here's a screenshot to illustrate. The red line is from ContactPoint.normal and the blue line is from RaycastHit.normal. Is this an instance of Unity hiding information to provide a simplified API? Or do standard 3D realtime collision detection techniques just not collect this information? And for the second part of the question, what's a surefire and relatively efficient way to get a surface normal for a collision? I know that raycasting gives you surface normals, but it seems I need to do several raycasts to accomplish this for all scenarios (maybe a contact point normal combination misses the collider on the first cast, or maybe you need to do some average of all the contact points' normals to get the best result). My current method Back up the Collision.contacts 0 .point along its hit normal Raycast down the negated hit normal for float.MaxValue, on Collision.collider If that fails, repeat steps 1 and 2 with the non negated normal If that fails, try steps 1 to 3 with Collision.contacts 1 Repeat 4 until successful or until all contact points exhausted. Give up, return Vector3.zero. This seems to catch everything, but all those raycasts make me queasy, and I'm not sure how to test that this works for enough cases. Is there a better way? EDIT If this really is just the way things are with 3D collision, an overview of why in the general case would be just as welcome as something specific to Unity.


Roguelike 2D Collision Detection I'm just a normal guy trying to do some basic collision detection but I suck at it. I either get stuck in a wall or I go in reverse in the wrong direction trying to update the player position to a non collision part. So here is how I check for collision and this function will return true or false. True if collision and false if not. roguelike.player.collision function() var player roguelike.player for(var i 0 i lt roguelike.map.rooms.length i ) var room roguelike.map.rooms i if(player.x gt room.x amp amp player.x lt room.x room.width amp amp player.y gt room.y amp amp player.y lt room.y room.height) return false return true This function works just fine just like expected. But it's when I try to stop the player when he hits a wall is where I get bugs. When the player goes down and hits a wall he gets stuck there. Here is the function that updates the player position. roguelike.update function() var player roguelike.player Left if(player.moving.left amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Up if(player.moving.up amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() Right if(player.moving.right amp amp !player.collision()) player.x roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() down if(player.moving.down amp amp !player.collision()) player.y roguelike.game.speedPerSecond(player.speed) else if(player.collision()) player.resetPosition() player.savePosition() So what I do is check what direction the player is moving and if there is no collision detected then the player is free to move. Otherwise if there is a collision I put the player position as the last position he was when there was no collision so he will be free to move. This works going left, up, and right, but not going down. Going down the player gets stuck in the collision and the resetPosition function doesn't put the player back in the safe zone. So I know there must be a better way. And I would appreciate your advice on what you think that way should be.


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.


Is it possible to detect contact with every frame change when using an animation in SpriteKit? Is it possible to detect contact with every frame change when using an animation in SpriteKit? For example, if I have two nodes of a person walking, I want to detect contact with the ground each time the frame changes (the character is walking on a surface). Just can't seem to get it. I've tried using a for loop to add a physics body and the contact and collision properties to each node, but that doesn't seem to work. It detects contact once, but that's it. Anyone have any ideas? Thanks in advance!


Get collision time between two moving, non uniform Axis Aligned bounding boxes I have a problem finding the exact time of collision of two possibly moving or static objects. Both objects have AABB data (HalfExtents, Min, Max, Center vector and stuff) and a velocity vector. The objects, as I wrote, can move, but must not to. How can I get the exact collision time from now? Could you give me please a pseudo code, or at least some directions how can be this solved?


What is the formula for the collision of two "stretched spheres"? In Smash Bros Melee, hitboxes aren't perfect spheres or boxes. They are, instead, a shape that looks like a continuous line of consecutive spheres I.e., the geometry can represented as Hitbox (fromPos V3, fromRad V3, toPos V3, toRad V3) Of course, one could emulate that by creating several spheres in a row, but it will probably not be the most efficient solution. So, what is a formula to test the collision of two of those hitboxes?


2D Tile based Game Collision problem I've been trying to program a tile based game, and I'm stuck at the collision detection. Here is my code (not the best ) void checkTile(Character c, int map) int x1,x2,y1,y2 Character position in the map c gt upY (c gt y) TILE SIZE Top left corner c gt downY (c gt y c gt h) TILE SIZE Bottom left corner c gt leftX (c gt x) TILE SIZE Top right corner c gt rightX (c gt x c gt w) TILE SIZE Bottom right corner x1 (c gt x 10) TILE SIZE 10px from left side point x2 (c gt x c gt w 10) TILE SIZE 10px from right side point y1 (c gt y 10) TILE SIZE 10px from top side point y2 (c gt y c gt h 10) TILE SIZE 10px from bottom side point Top if (map c gt upY x1 gt 2 map c gt upY x2 gt 2) c gt topCollision 1 else c gt topCollision 0 Bottom if ((map c gt downY x1 gt 2 map c gt downY x2 gt 2)) c gt downCollision 1 else c gt downCollision 0 Left if (map y1 c gt leftX gt 2 map y2 c gt leftX gt 2) c gt leftCollision 1 else c gt leftCollision 0 Right if (map y1 c gt rightX gt 2 map y2 c gt rightX gt 2) c gt rightCollision 1 else c gt rightCollision 0 That calculates 8 collision points My moving function is like that void movePlayer(Character c, int map) if ((c gt dirX LEFT amp amp !c gt leftCollision) (c gt dirX RIGHT amp amp !c gt rightCollision)) c gt x c gt vx if ((c gt dirY UP amp amp !c gt topCollision) (c gt dirY DOWN amp amp !c gt downCollision)) c gt y c gt vy checkPosition(c, map) and the checkPosition void checkPosition(Character c, int map) checkTile(c, map) if (c gt downCollision) if (c gt state ! JUMPING) c gt vy 0 c gt y (c gt downY TILE SIZE c gt h) if (c gt leftCollision) c gt vx 0 c gt x (c gt leftX) TILE SIZE TILE SIZE if (c gt rightCollision) c gt vx 0 c gt x c gt rightX TILE SIZE c gt w This works, but sometimes, when the player is landing on ground, right and left collision points become equal to 1. So it's as if there were collision coming from left or right. Does anyone know why this is doing this?


What is the correct formula for penalty forces? I am trying to add penalty forces between two hard body objects, so when they collide they move in a realistic way. What I have so far is this var totalMass aMass bMass var temp (aMass totalMass aVelocity) (bMass totalMass bVelocity) newVelocityB (bMass totalMass bVelocity) (aMass totalMass aVelocity) newVelocityA temp Originally I thought this was correct and it seems to work for the most part. However, this doesn't seem to be flawless. For example, if the collided object is a vertical wall (represented with a mass of infinity), the wall's velocity of (0,0) will be the final result. So, for an object moving diagonally with a velocity of (10,10) and hitting the wall, will result in a velocity of (0,0). In my case I would expect that the y component of the velocity remains 10, and it keeps sliding up the wall. Can anyone tell me if I'm on the right path, and how I can modify my formula to make sure that the y velocity does not become 0? I have considered that the collision normal of the wall could be important (in this example 1, 0 ), or the perpendicular of the normal, however I still have not figured out how to apply it in this formula. Multiplying by the perpendicular of the normal was my first idea, but this isn't the correct answer.


2D game collision response SAT minimum displacement along a given axis? I'm trying to implement a collision system in a 2D game I'm making. The separating axis theorem (as described by metanet's collision tutorial) seems like an efficient and robust way of handling collision detection, but I don't quite like the collision response method they use. By blindly displacing along the axis of least overlap, the algorithm simply ignores the previous position of the moving object, which means that it doesn't collide with the stationary object so much as it enters it and then bounces out. Here's an example of a situation where this would matter According to the SAT method described above, the rectangle would simply pop out of the triangle perpendicular to its hypotenuse However, realistically, the rectangle should stop at the lower right corner of the triangle, as that would be the point of first collision if it were moving continuously along its displacement vector Now, this might not actually matter during gameplay, but I'd love to know if there's a way of efficiently and generally attaining accurate displacements in this manner. I've been racking my brains over it for the past few days, and I don't want to give up yet! (Cross posted from StackOverflow, hope that's not against the rules!)


Fast self collision intersection detection algorithm for tetrahedral meshes I want to play with deformation of tetrahedral mesh (soft body simulation) but I need help with self collision detection stuff. I found SOFA collision detection but I'm not sure that it fits for self intersection of a tetrahedral mesh. Can anyone suggest me good algorithm for self collision detection? As far as I can understand, something like BVH of tetrahedra can help me, but it would be great if somebody with expertise shows me right direction.


What is the meaning of this line algorithm? I have been looking at codes of several open source 2d games and I have found this function. GetLineCollisionHit(Vector2 Position1, int Width1, int Height1, Vector2 Position2, int Width2, int Height2) int tile1X Position1.X Width1 16.0) int tile1Y Position1.Y Height1 16.0) int tile2X Position2.X Width2 16.0) int tile2Y Position2.Y Height2 16.0) do int dx Math.Abs(tile1X tile2X) int dy Math.Abs(tile1Y tile2Y) if (tile1X tile2X amp amp tile2Y tile1Y) return true if (dx gt dy) if (tile1X lt tile2X) tile1X else tile1X (check collision) else if (tile1Y lt tile2Y) tile1Y else tile1Y (return true if collision) while (true) return false What is really checking is if there is any collision of solid tiles between two points, for this look for the line between the two tiles. But I do not know if it is a coding problem since it is not implementing neither Bresenham's line algorithm nor DDA or similar. So what are you trying to find in this line dx dy? What sense does it have to advance x while x y since that way a line is not correctly created.


AS3 Rect Rect Collision Basically, my game has the player's attack hitbox change based on the attack being performed. I tried to make a simple collision test that takes an enemy's coordinates and have it check to see if it's within the range of the player. I don't want to resort to using Sprites and use hitTest() since efficiency is an issue. Anyway, the problem lies in the fact that the function below always returns true (even when the player is nowhere near the enemy). private function quickHitTest(boxLeft int, boxRight int, boxTop int, boxBottom int, rangeWidth int, rangeHeight int) Boolean return ((boxLeft gt (300 (rangeWidth 2)) amp amp (boxBottom gt (450 (rangeHeight 2)) boxTop lt (450 (rangeHeight 2)))) (boxRight lt (300 (rangeWidth 2)) amp amp (boxBottom gt (450 (rangeHeight 2)) boxTop lt (450 (rangeHeight 2))))) I having difficulties finding the source of the problem. All help is appreciated.


CCSprite x and y comparison I have 2 CCSprites and I want to tell if their x and y are equal I tried this if(sam.position.x tom.position.x amp amp sam.position.y tom.position.y) NSLog( "Hooray!") Although I do not think this is the right way to do this. Could anyone help me? Thanks. ALSO The CCSprites are named sam and tom.


How to build bullet (hit) damage detection in Augmented Reality to a real life person acting as an opponent? I am building an Android AR game using ARcore 1.18 in Unity 2019.4.5f1 (LTS). Now I want to create something like bullet damage detection just like it is built in a normal Unity 3D game. Of course, the biggest problem is how can I even detect the real person's hitbox like it is done in a normal game? I need to somehow be able to attach the bullet damage script to the body of the real life person in real time. Has anyone tried this before? How can we achieve this? I understand if I might not get a spoonfed tutorial but some help towards what should I be doing to achieve this will be greatly appreciated. I see some other FPS Augmented Reality games which either uses Laser Tag (Father.io) or Barcodes to scan the opponents. These are definitely some great ideas to create an FPS game experience but still, if possible, I want to try it with just the mobile camera without any external support. I am ready to bear some accuracy loss )


How can I determine which direction a 2D collision is occurring from? The problem is as follows Think 2D Zelda (Links Awakening, A Link to the Past) style movement where you can run into walls from any of the four cardinal directions, or basically up, down, left, and right. The difference between my movement and these games is I want to allow for diagonal movement as well. When the player collides with a wall on the left, for example, if he is pushing left and up I want him to stop moving left but continue moving up. The problem I am having is my code currently detects the collision as both an upwards and a left collision so the player simply stops. What is the approach I should take to remedy this? bool canCollideLeft false bool canCollideRight false bool canCollideUp false bool canCollideDown false if (HeroRect.Left gt OldHeroRect.Left) canCollideLeft false canCollideRight true if (HeroRect.Left lt OldHeroRect.Left) canCollideLeft true canCollideRight false if (HeroRect.Bottom gt OldHeroRect.Bottom) canCollideUp false canCollideDown true if (HeroRect.Bottom lt OldHeroRect.Bottom) canCollideUp true canCollideDown false foreach (RectangleItemProperties rectangle in CollisionRectangles) Rectangle CollisionRect new Rectangle((int)rectangle.Position.X, (int)rectangle.Position.Y, (int)Math.Abs(rectangle.Width), (int)Math.Abs(rectangle.Height)) if (HeroRect.Intersects(CollisionRect)) if (canCollideDown amp amp HeroRect.Bottom gt CollisionRect.Top amp amp HeroRect.Bottom lt CollisionRect.Bottom) hero.position.Y OldHeroRect.Location.Y if (canCollideUp amp amp HeroRect.Top gt CollisionRect.Top amp amp HeroRect.Top lt CollisionRect.Bottom) hero.position.Y OldHeroRect.Location.Y if (canCollideLeft amp amp HeroRect.Left lt CollisionRect.Right amp amp HeroRect.Left gt CollisionRect.Left) hero.position.X OldHeroRect.Location.X if (canCollideRight amp amp HeroRect.Right gt CollisionRect.Left amp amp HeroRect.Right lt CollisionRect.Right ) hero.position.X OldHeroRect.Location.X In summary the code compares the old position with the new position to see which direction we have moved and checks for a potential collision there. So if we move up and to the left, canCollideLeft and canCollideUp will be true. I am pretty sure this is where my problem lies and I need to better check which direction I am colliding from. Any thoughts or insight?


Bounding box of a rotated rectangle (2d) I can see this has been asked before in various ways. I am struggling to work it out though hence asking again. 2d sprite that moves and rotates. I'm looking to contain it in a bounding box as it appears that is the most efficient way to do collision detection. I had no problems getting it to work without rotation but that is simple! Now the sprite rotates I can't seem to find the right way of writing the code. To create a bounding box for the sprite, my understanding is I need to work out the 4 corners of the sprite after rotation and use these to work out the width height of the correctly sized bounding box. I've used the article here http msdn.microsoft.com en us library dd162943(v vs.85).aspx specifically the formula x' (x cos A) (y sin A) y' (x sin A) (y cos A) The code I'm currently using x1 (positionX Math.cos(rotation)) (positionY Math.sin(rotation)) y1 (positionX Math.sin(rotation)) (positionY Math.cos(rotation)) x2 (positionX width 2 Math.cos(rotation)) (positionY height 2 Math.sin(rotation)) y2 (positionX width 2 Math.sin(rotation)) (positionY height 2 Math.cos(rotation)) positionX and positionY is the current top left hand corner position of the sprite. rotation is the radians the sprite has been rotated by (and rotation is from the centre). width and height are of the sprite. I thought the code above would give me the co ordinates of the top left and top right corners of the rectangle, rotated appropriately. However, on my canvas, I'm drawing a line from x1,y1 to x2,y2 and it doesn't follow the sprite at all! Any suggestions? Sorry for the long post! Cheers!


How to get rid of an image upon collision detection in SDL? I am fairly new to SDL in C, but I have written a simple game whereby a character has to reach the end of a level and avoid bad stars on the way. If he hits a star, he dies. There are also good stars he can collect and get points. I have set up my point system so now when he hits a good star, he should get a point. However, when he hits a star, he actually gets lots of points, as long as he is touching the star, which I don't want. I think that what's happening is because the stars are moving and he rubs up against the stars each pixel he moves counts as a new collision so he gets a point per collision. Ideally, he should only get one point per star. So I have two problems 1) I need to figure out how to make it so that he can only get one point when he hits a star. 2) Since he is supposed to be 'collecting' the stars, I want to make the star disappear when he collects it. So it's similar to most of these types of games, whereby, the player collects something, it disappears and they get a point. EDIT This is struct I've made typedef struct int x, y, w, h, baseX, baseY, mode float phase Goodstar I've then referenced it in another struct like so Goodstar goodStars GOOD STARS SDL Texture goodStar GOOD STARS is equal to 100. And then here's my collision detection code Check for collision with good stars for (int i 0 i lt GOOD STARS i ) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points break So right now it only checks for a collision and then adds a point. EDIT 2 This is the code you suggested and it works for (int i 0 i lt GOOD STARS i ) if (!game gt goodStars i .awarded) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points game gt goodStars i .awarded 1 break And this is my initialisation code Initialise stars for (int i 0 i lt GOOD STARS i ) game gt goodStars i .baseX 320 random() 38400 game gt goodStars i .baseY random() 480 game gt goodStars i .mode random() 2 game gt goodStars i .phase 2 3.14 (random() 360) 360.0f game gt goodStars i .awarded 0


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.


Efficient Collisions Iteration? My project has upwards of 3000 2D objects but not all of them collide with each other. Between each object that can collide, a CollisionPair is created and stored inside a flattened array. Currently, a MaxObjects is defined for accessing the flattened array. Unfortunately, when iterating over this array for collision checks, I get a lot of overhead from the for loop and null checks. Is there a more efficient way, both in memory and performance, to store and access CollisionPairs? Note Many of these objects are axis aligned boxes how does Minecraft handle these collisions?


Bounding Box Collision Glitching Problem (Pygame) So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better). Here's the whole code from pygame import DONE False screen display.set mode((1024,768)) class Thing() def init (self,x,y,w,h,s,c) self.x x self.y y self.w w self.h h self.s s self.sur Surface((64,48)) draw.rect(self.sur,c,(self.x,self.y,w,h),1) self.sur.fill(c) def draw(self) screen.blit(self.sur,(self.x,self.y)) def move(self,x) if key.get pressed() K w or key.get pressed() K UP if x 1 self.y self.s else self.y self.s if key.get pressed() K s or key.get pressed() K DOWN if x 1 self.y self.s else self.y self.s if key.get pressed() K a or key.get pressed() K LEFT if x 1 self.x self.s else self.x self.s if key.get pressed() K d or key.get pressed() K RIGHT if x 1 self.x self.s else self.x self.s def warp(self) if self.y lt 48 self.y 768 if self.y gt 768 48 self.y 0 if self.x lt 64 self.x 1024 64 if self.x gt 1024 64 self.x 64 r1 Thing(0,0,64,48,1,(0,255,0)) r2 Thing(6 64,6 48,64,48,1,(255,0,0)) while not DONE screen.fill((0,0,0)) r2.draw() r1.draw() If not intersecting, then moves, else, it moves in the opposite direction. if not ((((r1.x r1.w) gt (r2.x r1.s)) and (r1.x lt ((r2.x r2.w) r1.s))) and (((r1.y r1.h) gt (r2.y r1.s)) and (r1.y lt ((r2.y r2.h) r1.s)))) r1.move(1) else r1.move(0) r1.warp() if key.get pressed() K ESCAPE DONE True for ev in event.get() if ev.type QUIT DONE True display.update() quit() The problem In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast. In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them. The code problem illustrated When the player goes towards the wall (Fine). When the player goes towards the wall and press the opposite direction. (It glitches through). Here is the logic I've designed before implementing it I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching possibilities. What do you suggest?


How do I detect multiple sprite collisions when there are 10 sprites? I making a small program to animate the astar algorithm. If you look at the image, there are lots of yellow cars moving around. Those can collide at any moment, could be just one or all of them could just stupidly crash into each other. How do I detect all of those collisions? How do I find out which specific car has crash into which other car? I understand that pygame has collision function, but it only detects one collision at a time and I'd have to specify which sprites. Right now I am just trying to iterate through each sprite to see if there is collision for car1 in carlist for car2 in carlist collide(car1, car2) This can't be the proper way to do it, if the car list goes to a huge number, a double loop will be too slow.


Separation of axis theorem implementation at normals This might be more of a math question, but it relates to the development of a simple physics engine I am trying to create. I have been stumped on this for about a week now, and have been unable to find an answer in any of the SAT tutorials. (http www.metanetsoftware.com technique tutorialA.html toc, http gamedevelopment.tutsplus.com tutorials collision detection using the separating axis theorem gamedev 169, etc.) I understand how SAT is supposed to work, however I am little confused on the math. First, I am finding my normals like so Block.prototype.findNormals function () var axisVectors new Array() var vertices this.Properties.Vertices var keys Object.keys(vertices) for( var i 0 i lt keys.length i ) var last x 0, y 0 axisVectors.push( xComponent (vertices keys i .y last.y), yComponent (vertices keys i .x last.x) ) last x this.x, y this.y return axisVectors I am then precede to project each vertex of the shapes I am testing on those normals. The problem occurs, and the part of the math that I am not fully understanding, is when I have a situation like so axis ( 5, 6) vertex (6, 5) math.dot(vertex, axis) This results in 0. Thus my min value for shape1 is always 0. And this results in a false collision. Can anyone explain the math a little better?


What kind of physics to choose for our arcade 3D MMO? We're creating an action MMO using Three.js (WebGL) with an arcadish feel, and implementing physics for it has been a pain in the butt. Our game has a terrain where the character will walk on, and in the future 3D objects (a house, a tree, etc) that will have collisions. In terms of complexity, the physics engine should be like World of Warcraft. We don't need friction, bouncing behaviour or anything more complex like joints, etc. Just gravity. I have managed to implement terrain physics so far by casting a ray downwards, but it does not take into account possible 3D objects. Note that these 3D objects need to have convex collisions, so our artists create a 3D house and the player can walk inside but can't walk through the walls. How do I implement proper collision detection with 3D objects like in World of Warcraft? Do I need an advanced physics engine? I read about Physijs which looks cool, but I fear that it may be overkill to implement that for our game. Also, how does WoW do it? Do they have a separate raycasting system for the terrain? Or do they treat the terrain like any other convex mesh? A screenshot of our game so far


Reacting to rectangle on rectangle collisions I don't know how to react to collisions between two axis aligned rectangles that have x, y, width and height values (x and y are from the centre of the box) to make them simply not overlap. I figured I'd just make them move away from each other depending on how far they intersect in the opposite direction (left, right, up or down) of where they collided. If I check for collisions only on the x axis or only on the y axis it works fine, but when checking for both collisions crazy stuff happens. This code executes when the first box collides with the second. It's in lua but feel free to answer in anything that isn't to too counter intuitive. if box1.x lt box2.x then box1.x box2.x (box1.width 2) (box2.width 2) end if box1.x gt box2.x then box1.x box1.x (box1.x box2.x (box1.width 2) (box2.width 2)) end if box1.y lt box2.y then box1.y box2.y (box1.height 2) (box2.height 2) end if box1.y gt box2.y then box1.y box1.y (box1.y box2.y (box1.height 2) (box2.height 2)) end


Collision test solution for hack slash game I want to ask you what is the best way to deal with collisions in hack amp slash game, I know that collisions must be very accurate. My first idea is to use sphere bounds ( I making hack amp slash in 3d), but how to deal with hitting with sword some enemy, do you know some better solution for this type of game ?


Realistic 3D Collision Detection Implementation I understand how box collision, sphere collision, and other such collisions work. However, how would one implement realistic 3D collisions? That is, objects would interact with one another as they would in real life. For example, take a rod and a torus. Assume that the thickness of the rod is smaller than the hole in the torus. With simple collision systems, as far as I know, inserting the rod into the hole of the torus would result in a collision detection. In reality, no collision would take place. Hopefully, that explains what I am looking for.


How collisions should be handled in terms of design I'm not sure how should I design the collision part in order to respond the all the game requests. First that comes in mind is 1. Update the game objects positions 2. Check the collision 3. Update the positions based on collision data Now the problem is what if an object needs to know when it did collide in order to perform some actions. Lets say a player picks a chests, so he must not be bounced by the chest and also all the player, chest and cut scene sequence need to be triggered. So if I do everything in collision routine (without triggers) then all the game logic is biased toward one game and is not flexible, its need to be adapted rewritten for each game. If I use triggers and call every object collision function what if player needs to move backward and collisions needs to be rechecked, do I need to make a flag to recalculate and collisions for objects that has this flag set until collisions are done? Or do I check for chest collision in player update method (before the global collision routine) and do all the calculations there... but what if I don't want the player to react to collision if chest is closed and react if its opened (not just a player chest collision pair setting)? What is the best way to implement this kind of system that will be flexible for future games and in the same time respond to all requests of game design (in this case the example I wrote above, player chest)


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


Sprite Kit containsPoint for SKPhysicsBody? I have a ball bouncing around the screen. I can pick it up and drag it onto a "bucket". When my touches finish, I use the containsPoint function to check and see if I have dropped the ball onto the bucket. This works fine, however, I actually want to check whether the ball is dropped onto the bucket node's physics body because my "bucket" is actually just an oval, and so I've applied a physics body which is the same shape as the oval, so that the white space around the oval isn't included in the physics simulation. I can't seem to find a "containsPoint" function for physics bodies. Can anyone advise on how I'd check for this? To summarise, I want to drop a node, onto a specific part of another node (or its physics body) and trigger an event. Thanks in advance.


Handling strange physics behaviour while sliding between coplanar surfaces We've got a character setup based around manually resolving collisions, and we're using bullet to do so. Our characters have a kinematic rigidbody to push things around, but their movement and positioning is done using a separate (pair caching) ghost object. Every physics tick we iterate over all contacts for that ghost and resolve collision either by depenetrating 100 when it's ground, or by depenetrating gradually not at all with walls or other characters. We then apply our ghost's new position to the kinematic rigidbody so that can interact with other physics objects. Unfortunately, when moving around a flat world made up of a bunch of coplanar blocks, when the characters moves from one block to another it will often do one of two things Fall through the cracks Get bumped upward a significant distance (we're talking up to half a unit meter with a character that is 2 units meters tall) Debugging this tells me sometimes these contact points are unexpected, and not something I want to resolve by depenetrating 100 . Gravity moving the character downward can result in a contact point that is closer to the side of the terrain block than the top, and it will give you a normal distance accordingly (blue arrow). Resolving that with 100 depenetration will just push you in between the blocks, while not counteracting the gravity forces. This would explain the falling through the cracks. But I don't know why I sometimes get contact points with normals pointing straight up, but with a distance that would place the collider far above the ground (purple arrow). I've come to the point where I feel like my only option to handle character movement like this is by not colliding with the ground at all, and just spherecast downwards at the character's position on the horizontal plane just to place it down on the ground properly. Now obviously I want to get rid of this behaviour. And seeing how you don't see this happen in many games, I'm lead to believe others have solved this issue somehow. Has anyone here encountered similar issues, and how did you go about fixing them?


Collision detection with moving objects I searched a lot about this problem. I found many answers here in Stack Exchange but none of them really answers when positions for objects get updated. For a game with fixed size map and that has all the time 200 moving objects with different sizes (bullets, players, NPCs, etc.) 100 static objects with different sizes (obstacles, health packs, etc.) I am looking for an efficient way to do collision detection. Here is the pseudo code in each game loop (15 ms) collect movement commands and apply force on objects of those commands loop with very small physics time steps (0.1 ms) for object in movingObjects get objects that might collide with current object gt 1 check if any collision occurs for object in movingObjects update position of object (based on command collected) gt 2 So I get the objects that might collide with given object. It is done using a data structure like quadtree or spatial hashing grid (or something else that makes more sense). Object's position is updated. Now, how do I inform the data structure that this object's position is updated? I don't want to remove and insert. That is not efficient at all. I feel like quad tree and spatial hash implementations all over the internet are avoiding this problem. I would also appreciate if you tell me my pseudo code above is problematic. I have the feeling this uses too much CPU.


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.


Soft Body Collision with Box2d (libGDX) I've made a few classes to create soft body objects in libGDX using Box2D (specifically a circle and rectangle similar to these links). The objects are constructed of a number of circle shaped Box2D bodies (hereafter deform points) connected together by distance joints which allow the object to "deform" when the deform points move around. Collision works more or less fine when the objects are colliding with other standard Box2D rigid bodies such as a box polygon (what they're sitting on) The problem starts when two soft bodies collide. As you can probably guess from the way they're constructed, the two often pass through each other since the deform points for which Box2D handles collision are small and spaced apart, so they easily don't collide when the two soft bodies should. If the two bodies are placed like seen on the left in the following image, the circle passes through the square, rather than bouncing off the top of it as it should I've tried solving the problem (methods shown below) by tessellating the bodies more so that the deform points are closer together (left), which seems far too resource intensive and didn't affect much anyway. Then I tried enlarging the size of the deform points to fill the gaps (middle), which worked perfectly for the collision but as you can see caused problems mapping the texture to the object since the textures don't appear to collide. After that I tried to bound the outside of the object using polygon bodies connected between deform points using revolute joints, this works with the texture better and does prevent objects from falling through each other, but it stops the object from deforming properly. I can't think of any more ways to tackle this problem, but I'm very new to Box2D and libGDX and maybe I'm overlooking a much more simple solution. I'll give any ideas a shot.


Circle inside circle collision In one of my projects I have a game area in the shape of a circle. Inside this circle another small circle is moving around. What I want to do is keep the small circle from moving outside the bigger one. Below you can see that in frame 2 the small circle is partly outside, I need a way to move it back to just before it is about to move outside. How can this be done? Also, I need the collision point along the arc of the big circle so that I can update the small circle's velocity. How would one go about calculating this point? What I would like to do is before moving the small circle, I predict its next position and if it is outside I find the time of collision between t 0 and t 1 (t 1 full time step). If I have the collision time t then I just move the small circle during t instead of a full time step. But again, the problem is I don't know how to detect at that time the collision occurs when it comes to two circles and one being inside the other. EDIT Example of collision point (green) I want to find. Maybe the picture is a bit off but you get the idea.


What is the most efficient way to determine collision path I am trying to create a game in which I need to know if two objects will collide in the future, and when. I have both object's position, radius (they are circles) and velocity. A specific example of where this could be used is in a game with an asteroid field. The asteroids position, radius and a constant linear velocity. I want to determine if on their current trajectory, will they crash. If yes, in how much time. I have tried to set up the position of the objects as a function of time P(t) o v(t) Where P(t) is the new position, o is the original position v is the velocity and t is time. Using this for both objects and attempting to solve for t, I get a very messy and long equation.


Why do I get a segmentation fault on launch with this code? I am currently writing a pong clone in C with SDL on top. Currently, I have hit a roadblock. If I add a new variable, my game won't launch, and will give "segmentation fault" in the debug terminal. When I comment out a variable, the following code gives no errors, but otherwise, it just returns "Segmentation Fault" on the debug terminal after flashing the frame the game would normally appear in. ifdef cplusplus include lt cstdlib gt else include lt stdlib.h gt endif ifdef APPLE include lt SDL SDL.h gt else include lt SDL.h gt endif include "SDL SDL image.h" include "SDL SDL framerate.h" include "checkcol.h" Uint8 keystates SDL GetKeyState( NULL ) int main ( int argc, char argv ) initialize SDL video if ( SDL Init( SDL INIT EVERYTHING ) lt 0 ) printf( "Unable to init SDL s n", SDL GetError() ) return 1 atexit(SDL Quit) make sure SDL cleans up before exit create a new window SDL Surface screen SDL SetVideoMode(640, 480, 16,SDL HWSURFACE SDL DOUBLEBUF) if ( !screen ) printf("Unable to set 640x480 video s n", SDL GetError()) return 1 SDL Surface left IMG Load("left.png") SDL Surface right IMG Load("right.png") SDL Surface ball IMG Load("ball.png") if (!left !right !ball) printf("Unable to load a png s n", SDL GetError()) return 1 centre the bitmap on screen SDL Rect leftr leftr.x 0 leftr.y (screen gt h left gt h) 2 SDL Rect rightr rightr.x (screen gt w right gt w) rightr.y (screen gt h right gt h) 2 SDL Rect ball1 ball1.x ((screen gt w ball gt w) 2) 50 ball1.y (screen gt h ball gt h) 2 SDL Rect ball2 ball2.x ((screen gt w ball gt w) 2) 50 ball2.y (screen gt h ball gt h) 2 bool b1xm 0 describes ball 1's movement in x bool b1ym 0 bool b2xm 1 bool b2ym 1 unsigned short lscore 0 unsigned short rscore 0 FPSmanager manex SDL initFramerate( manex ) you want the top framerate to be 60 for example SDL setFramerate( manex, 60 ) program main loop bool done false while (!done) this is where my main code is end main loop free loaded images SDL FreeSurface(left) SDL FreeSurface(right) SDL FreeSurface(ball) all is well printf("Exited cleanly n") return 0


Are SDL games trivially portable from Linux to Windows? I have a small game made with SDL2 and I want to port it to Windows. Would I hav eto write a lot of ifdefs to port it or will the very same code work on Windows and Linux? Or is it more complicated? Sorry if these are silly questions. I couldn't find existing resources on porting SDL games between desktop systems and I've never done this before!


Multiple keypresses causing wierd results in SDL I have been building a pong clone. I've been using a mixture of peoples different code to understand the way they structure their games as well as reading on game patterns. Currently I've gotten to draw a paddle on the screen and the player can move it with the keyboard no problem. The issue comes when a player presses a button that is not 'Up' or 'Down'. For instance when the player holds the 'Up' key the paddle travels upwards, but if they simultaneously hold the 'Right' key it causes the paddle to fly downwards at a much greater speed. My keyboard checking code is void GameLoop Input(SDL Event amp ev) if (ev.type SDL KEYDOWN) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(true) player1 gt velocity 10 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(true) player1 gt velocity 10 else if (ev.type SDL KEYUP) if (ev.key.keysym.scancode SDL SCANCODE DOWN) player1 gt IsMoving(false) player1 gt velocity 0 if (ev.key.keysym.scancode SDL SCANCODE UP) player1 gt IsMoving(false) player1 gt velocity 0 The GameLoop is ran within loop that is configured to run at 60FPS. You can see this in this code block here int main(int argc, char argv) Initialise the app and SDL App app(SDL INIT VIDEO) GameLoop game double lastTime 0.0, currentTime SDL Event e while (app.isRunning()) if (SDL PollEvent( amp e)) if (e.type SDL QUIT) app.exit() currentTime SDL GetTicks() 1000.0 if (currentTime gt lastTime 0.01666667) game.Input(e) game.Update() game.Render() lastTime currentTime return 0 This is the paddles update code void Paddle Update() if(moving true) rect.y velocity velocity 50 X rect.x Y rect.y I'm unsure of what is causing the paddle to behave so strangely. Any insight given into this problem or even just the way I've approached this problem would be appreciated.


SDL PollEvent very slow on SDL2, but works fine on SDL1.2 I have this simple app that displays a screen and handles the quit event while( SDL PollEvent( amp e ) ! 0 ) User requests quit if( e.type SDL QUIT ) quit true If I compile this with SDL1.2 it runs fine, the quit event is handled immediately. However if I compile it for SDL2, then it takes 5 seconds to get that event. And not just quit, but other events also, like mouse. With sdl2 it takes 95 of the cpu, while with sdl1.2 it's 30 40 . The cpu is dual core, 1.2 ghz (pandaboard). I suspect something, but I'm not 100 sure I'm running this on ubuntu 12.04 which natively supports only sdl1.2. So I had to compile sdl2 from source code, as it's not available in that ubuntu. Could this be the reason? Or any other clues what might be wrong? Thanks!


SDL Surface clipping mask I am creating a GUI for my game, so I use some buttons like . So you can see it is only text surrounded by a rectangle. But I currently use a huge png image with all the buttons I need arranged as I want it, it is really inefficient, so how can I upload a single smaller image of the rectangle, a sample of the gradient I want and use SDL tff to create a surface. Say I copy the rectangle and the text in an SDL Surface, it should have two colors (black and white), now make white pixel transparent and black pixels to be replaced with the gradient to create the buttons and place them using SDL Rects.


Where can I get correct pitch parameter for SDL RenderReadPixels function in SDL2? I have a texture created with SDL TEXTUREACCESS TARGET access and I want to get all its pixels with SDL RenderReadPixels() function. One of the function parameters is pitch and I don't really know where can I can get it. Texture is created with dimensions of a previously created surface, but function call with surface gt pitch as pitch parameter generates EXC BAD ACCESS. Texture and surface dimensions are 800x600, and surface gt pitch returns 3200, which is strange for me, because I thought that pitch is the width of the texture in memory and expected surface gt pitch to be something like 1024.


What is missing from SDL for it to gain more widespread adoption? As I understand, SDL offers abstractions that let you make windows, handle input and audio much easier than doing so directly with the low level APIs provided by several operating systems. However, it seems that a lot of games, both indie and AAA, don't use it, and I would like to know why. This makes me suspect that there may be areas where SDL is lacking, such as features, performance, or robustness, when compared to platform specific APIs. Apart from platform support, that is, considering only the platforms SDL supports, I do not understand what would keep a developer from using SDL for their game, since I feel like, based on my admittedly limited knowledge, it'd be much smarter to use SDL on the platforms that do support it.


State machine in C for SDL game I want to create a state machine for menu in my SDL game. So this is my code without the SDL I just want to ask if this is a good way to create it. here is a code include lt stdio.h gt include lt windows.h gt enum states Menu, Game, Game over, Exit int main() int game is running 1 enum states state Menu while(game is running 1) switch(state) case Menu state Game printf( quot menu screen with play and exit button. n quot ) need to add if exit or play is pressed if exit then exit program if play than you know... break case Game state Game over printf( quot after play button is pressed game screen will show up. n quot ) after this i will come back to menu. break case Game over state Exit printf( quot screen after game. n quot ) break case Exit printf( quot turn game off. n quot ) this will be in the if function with a game. game is running 0 break Sleep(1000) sleep for a second just for test return 0


Is there a way to duplicate the windows desktop zooming in SDL to make low res pixels look like stylyzed cartoon art? When you hit the Win key and numpad plus key at the same time it opens the desktop magnifying glass and the effect of this on low res pixel art is to make it look like super cool stylized cartoon art. I want the game to look like this all the time. Is there a way to do this permanent i SDL or DirectX or OpenGL? How I have achieved this image is to run the game in a small windows and have the windows 10 magnifying glass hoover over it and I hit print screen. And I want the game to look like this all the time in full screen. Ps. This is the Gradius 3 ship that I use for place holder graphics for question asking purposes.


Polling events with SDL results in stuttering response when dealing with multiple objects I'm new to SDL programming and I'm not quite sure I got how it handles events. Given an instance like this defined in quot game.c quot static struct SDL Window window SDL Renderer renderer BinaryTree objects game NULL, NULL, NULL (Which of course gets properly initialized) My game loop is defined in the same file as follows void game run() bool closeRequested false while(closeRequested false) SDL RenderClear(game.renderer) binaryTree startIteration(game.objects) while(binaryTree hasNext(game.objects)) GameObject gameObject (GameObject ) binaryTree getNext(game.objects) SDL Event event while(SDL PollEvent( amp event)) if(event.type SDL QUIT) closeRequested true else if(event.type SDL KEYDOWN) gameObject onKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE UP) gameObject onUpKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE DOWN) gameObject onDownKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE LEFT) gameObject onLeftKeyPressed(gameObject) if(event.key.keysym.scancode SDL SCANCODE RIGHT) gameObject onRightKeyPressed(gameObject) if(event.type SDL KEYUP) gameObject onRendering(gameObject) SDL RenderCopy(renderer, gameObject getTexture(gameObject), NULL, gameObject getDestination(gameObject)) SDL RenderPresent(game.renderer) game.objects contains every object which has to be rendered (via game.renderer) onto the the window (game.window). So, on each frame game.objects gets iterated on and for each element various functions get executed, before its texture is loaded to the renderer. Of course gameObject onRightKeyPressed() is called only if the right key was pressed, so if this function is defined as void gameObject onRightKeyPressed(GameObject gameObject) gameObject gt destination.x 1, On each frame that the right key is pressed, gameObject's texture will move by 1 pixel to the right. This works perfectly if game.objects contains only one element, but if a second element gets added, only the first one will smoothly respond to my input, while the other will move by 1 or 2 pixels just once in a while by keeping the right key pressed. It's like the first element contained in game.objects quot steals quot the input, so that when the second element's turn comes, there's no input for it to respond to. What did I do wrong?


Memory leak around SDL FreeSurface When I call my tile engine function, the amount of memory my program uses begins to spike at about 80 90 megabytes per second. The memory use continues to go up until the program crashes. The function is below. After tinkering with it, I figured out that I could reduce this bricking to about 15 megabytes per second if I called SDL FreeSurface every time I ran the function. But this confused me, because I thought that you are only supposed to use SDL FreeSurface when the program exits so that the images don't continue to occupy the memory. if I don't call SDL FreeSurface before I blit the tiles, do the previously blitted tiles continue to exist? If I don't how do I fix the aforementioned bug? The edit I made to bring the memory bricking down to 15 megabytes per second is commented out. SDL Surface loadedTile NULL SDL Surface modelIMAGE NULL void enviroment blitTiles(SDL Surface windowENVIRO, int tileAmount, int tileType , int tileXenviro, int tileYenviro, bool quitTiles) HDcounter 1 if(loadedTile ! NULL) SDL FreeSurface(loadedTile) loadedTile IBFobjectENVIRO.loadIMG("tileClipSheet.png") for(int tiles 0 tiles lt tileAmount tiles ) switch(tileType tiles ) Black square (unpassable) case 1 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 0, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break Grey square case 2 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 75, 0, 75, 75) break Brown square case 3 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 150, 0, 75, 75) break Invisible square (unpassable) case 4 IBFobjectENVIRO.blitIMG(tileXenviro 75, tileYenviro, windowENVIRO, loadedTile, 225, 0, 75, 75) HDcounter 1 forbiddenX HDcounter tileXenviro 75 forbiddenY HDcounter tileYenviro forbiddenSpriteWidth HDcounter 75 forbiddenSpriteHeight HDcounter 75 forbiddenSpriteDepth HDcounter 75 break tileXenviro 75 if(tileXenviro gt level1ObjectENVIRO.level1Width) tileYenviro 75 tileXenviro tileXenviro level1ObjectENVIRO.level1Width if(quitTiles true) SDL FreeSurface(loadedTile)


Should I cull off screen objects in SDL2 My game will have a large number of objects moving offscreen at any given time, can i just render them all with SDL RenderCopy even though they are off screen or should I only render them if they are on screen? I will probably have many hundreds or throusands of objects loaded at a time. My dev machine is quite overpowered for what I'm trying to do but I am conserned that I just won't notice a preformance drop that may affect players with less powerful computers. So, will checking if each object is on screen before drawing increase performance lower CPU load, or can I safely let SDL handle this with clipping?


Background color gradient with SDL I want to create a menu for a game using a color gradient as the background. Is there a way to create a gradient background instead of using an image for it (since I don't know what size the window will be, using an image is no option). Please note I need to achieve this using only the C standard library and the SDL, no other library and no C .


What does FPSManager.lastticks stand for in SDL gfx? I'm having trouble finding documentation on SDL gfx, and I can't figure this out. I've managed to use SDL gfx to automatically cap the framerate, and I it's working a lot better than my manual attempt (combining SDL Delay and SDL Getticks). Now I've been trying to learn more about it, and I stumbled onto something. Here's the whole struct typedef struct Uint32 framecount float rateticks Uint32 lastticks Uint32 rate FPSmanager Most variables in this struct are pretty straightforward, but I have no idea of what lastticks stands for. Does anyone know?


Why does SDL2 blur pixel art even with SDL HINT RENDER SCALE QUALITY set to 0? I am working on a game with SDL2 and having trouble turning off linear filtering when upscaling textures. My game has a bunch of 32x32 tiles. I used SDL RenderSetLogicalSize so that there is a one to one pixel mapping (i.e. my logical size is n 32 x m 32.) However, when the the whole scene is upscaled to fit the actual screen, it seems to be interpolated (blurry). I saw these two other posts (1, 2) which recommended using SDL SetHint(SDL HINT RENDER SCALE QUALITY, "0") . I did that, but nothing seems to change at all. It returns true and it is in fact changing the hint, but the rendering just doesn't change at all. I even tried setting it with priority but nothing changes. Any idea how to fix this? I am on Windows if that's relavent.


Problem getting mouse events while keys held down in SDL2 I'm attempting to write input capturing code using SDL2 on Windows. However, I'm running into a problem. Whenever a key is held down, the SDL event queue has no mouse movement, nor will the mouse move on my screen. Instead, The SDL event queue continually returns the key I am holding down as an SDL KEYDOWN event. Here is a simple example program which reproduces the problem exactly include lt SDL2 SDL.h gt include lt iostream gt int main(int argc, char argv) SDL Init(SDL INIT EVERYTHING) SDL Window window SDL CreateWindow("Moust Input Test", SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 640, 480, SDL WINDOW SHOWN) SDL Event event for( ) while (SDL PollEvent( amp event)) if (event.type SDL QUIT) SDL DestroyWindow(window) return 0 else if (event.type SDL MOUSEMOTION) int x, y SDL GetMouseState( amp x, amp y ) std cout lt lt "Mouse moved to " lt lt x lt lt " " lt lt y lt lt std endl else if (event.type SDL KEYDOWN) std cout lt lt "Code of key pressed " lt lt event.key.keysym.sym lt lt std endl return 0 What I would expect to happen is that, when I hold down a key (for example, 'a'), it prints exactly once Code of key pressed 97 And then, while they key is held down, if the mouse is moved, it prints every time the mouse is moved Mouse moved to wherever Instead, I'll keep seeing over and over again Code of key pressed 97 And I will not get any mouse movement whatsoever on the screen, nor will I get my mouse movement log printed, until I release whatever keys I am holding down. Anybody know how I can capture mouse movement while I have a key held down? The only thing I can think of which could possibly be relevant is I am compiling with MinGW using g Dmain SDL main test.cpp o test.exe L. lib SDL2 lmingw32 lSDL2main lSDL2 mwindows mconsole Thanks. Edit I've also just noticed that the problem persists even when the window is minimized if I am holding a key down in this text window while my program is minimized in another Window, the mouse stops working, though my program is not printing out the key code.