_id
int64
0
49
text
stringlengths
71
4.19k
18
Handle floating point precision errors in collision detection and resolution I am experimenting with a continuous collision detection and response of points on a tile map. This are my results for now I did this by shooting a ray (red line) from the current position (red circle) to the target position (green circle) and check all tiles which are on it using this algorithm. If the ray hits a solid tile I calculate the exact postion of the collision (yellow circle) and a new target positition depending whether the ray hit the solid tile vertically or horizontally in the other case I can simply set the current position to the target position and be finished because no collision occurred. Now I am shooting a second ray (blue line) to this new target position and check again for solid tiles on it. If a collision occurerd I set the current position to the ray hit position (cyan circle) and be finished. In the other case I only set the the current position to the new target position (cyan circle) because no collision occurred this time. Here the most important source code void update(float start x, float start y, float target x, float target y, float corrected x, float corrected y) float hit0 x float hit0 y LineTraceResult res0 line trace(start x, start y, target x, target y, amp hit0 x, amp hit0 y) switch (res0) case LINE TRACE NONE No collision occurred so the target position is valid and we can move to it. corrected x target x corrected y target y break case LINE TRACE VERT We hit a solid tile on the vertical edge. corrected x hit0 x corrected y target y float hit1 x float hit1 y LineTraceResult res1 line trace(hit0 x, hit0 y, corrected x, corrected y, amp hit1 x, amp hit1 y) if (res1 ! LINE TRACE NONE) There was a second collision on the corrected position so we need to adjust it. Because the x axis did not changed we don't need to change it. corrected y hit1 y break case LINE TRACE HORI We hit a solid tile on the horizontal edge. corrected x target x corrected y hit0 y float hit1 x float hit1 y LineTraceResult res1 line trace(hit0 x, hit0 y, corrected x, corrected y, amp hit1 x, amp hit1 y) if (res1 ! LINE TRACE NONE) There was a second collision on the corrected position so we need to adjust it. Because the y axis did not changed we don't need to change it. corrected x hit1 x break So in theory this all works great but in practice there are a lot of problems caused by the limited precision of floats. For example in this two cases One approach to "solve" this problem is to add some kind of padding often named Epsilon every time a collision occurs but this method seems to me not very accurate and dirty. So I am wondering how all the professional game developers are solving this kind of problem? EDIT This problems occurre because the hit position calculated by the ray can not be 100 exact so it could be for example that the y coordinate gets rounded from 6.9999 to 7.0001 and 6.9999 means tile 6 and 7.0001 means tile 7 so its a huge difference.
18
How do I resolve a collision of a circle with two rectangle corners? I'm writing a simple non physical one circle to many rectangles collision detector resolver. For collision detection, I'm using a very common algorithm, and it's working pretty well. For collision resolving, once a collision is detected, I calculate the penetration vector, and reactively move the circle in the opposite direction. Once again, it is working pretty well. However, when there are two adjacent colliders, and the circle is moving right in the place where the two colliders meet, the situation is more complex. This is a screenshot of the situation The white rectangles are the rectangle colliders (walls), the yellow circle is the circle collider (player), and the magenta lines are the vectors from the center of the circle to the closest point in each collider. The problem happens when I get a collision on more than one rectangle. As you can see in the picture above, the top rectangle will have a penetration vector which is not in the direction of the normal of the entire surface, and as such will create artifacts as the circle slides through the wall, depending on how I handle it. There are many solutions I have tried, but they all create artifacts. In particular, using any algorithm to pick only one collision and solving only for that one, may yield different solutions depending on the order in which they are evaluated, especially on cases where both collisions must clearly be chosen, like the following one Just for reference, these diagrams are meant to show a top down, not a side view of the playing field. Is there a known way to resolve such a collision correctly?
18
How to detect collision on specific part of the sprite node I have a spike and a ball is falling down, when the ball touches the top point of the spike, I want to make the ball invisible, and when it touches on the other part i.e on the sides I don't want to make it invisible. I have two sprite nodes Ball and spike. How can I make the collision detect only on specific part i.e only on top of the spike in spritekit?
18
Collision detection between 2 irregular shapes I need to implement a collision system for a vertical shotter and the bullets can have any type of shape i've implemented the shape class with an array of choords and an array of lines which have the references of start and end points in case the line is bezier it have an array of anchor points. so Line Choord Start,End Choord Anchors null ... Choord float X, Y ... Shape Choord Vertexs Line Lines ... i have to handle a collision like this anyone have a general idea for check collision with this type of shapes? and this model can work? i've tryed with SAT collisions but it works only for convex polygons.
18
Collision Detection in a big map? So I've been wondering lately... on games like pokemon (on ds and gba), How did they handle the collision of all those tiles in the map? Should all those collision checks running in the background slow down the game? Do they have it where the collision activates from a certain distance? Do they have a player event where the player is next to a tile that is not able to be walked on? If it is not possible to know the answer, could you give me a solution to that problem? I guess what I am really asking is how to handle collision of almost every tile in a big map.
18
How do I do 3d collisions in isometric game? I've wondered how to get basic collision detection working in an isometric game. I'm using panda3d which has very comfortable support for bullet, ode and a small builtin physics framework. The problem is that these naturally don't work with flat images. I'm using dynamically generated quads as canvases in the 3d coordinate system. Every image or texture is mapped on one of these. The idea is to create tiles with images and place them in 3 dimensions to let panda3d do the rendering. In order to place a tree on the screen I would generate one of the dynamic flat quads and map a texture with an image of the tree on it. Then I would move the quad to the desired position and everything's fine. Panda3d manages the correct rendering order. Up to now the player object simply walks through the environment. I need to implement basic collision detection in order to solidify the trees. Browsing through previous questions I've found this one How do I handle Isometric collision detection? Unfortunately the question only targeted collisions to prevent the player from falling through the ground and allowing him to jump on platforms. This can be done comfortably with panda3d's builtin physics. Here's a picture to show you what I want The ground itself is composed of a 10x10 grid of tiles. I've used the same texture for all of them. The tree is not a sprite that's rendered in 2d. It's actually a flat rectangle with a partially transparent tree texture. The white rectangle is my player object. With the standard 3d physics I could prevent the player from walking through the quad but the tree would still be perfectly flat. I thought about adding a "dummy mesh" to have 3d collisions but that would surely come pricey in terms of performance and would spoil the neat implementation of my 3d canvases. Is there a canonical way to get 3d collisions in an isometric game ? How would you do this ? Please answer this second question on behalf of panda3d. I know that this is probably rather complicated. A link to a good article would be perfect. If you want to have a look at my code, you might want to read this question How do I use setFilmSize in panda3d to achieve the correct view? UPDATE Here's another picture that might depict the problem better
18
Collision response callback First at all, I'm not asking how to handle or detect collision. I already have that. My actual situation is, I have a system collision and I detect the collisions. Every collision detected is store as a message containing the two entities colliding with some information like type of collision or something. Later, all messages is processed. I'm trying to figure out how to implement the reaction of the entities in every collision with that message. In the game a collision can trigger an action like talking with another, change the level, kill the character, store an object, not letting go... I don't want to hard code the calls and methods if possible (in my ideal world,I can define even the behaviour in an xml an read from that!). My first approach is a class where I store a list of possible actions callback functions and attach it to the entity as a component. When a collision succed, I go to the entity and depending of the collision, execute the correspond callback. Still I don't know how to determine the callback to execute or where I must code the behaviour. Any ideas? What you think about this approach? By the way, I'm building everything from scratch, with c and SFML and following the entity system approach, for educational purpose.
18
When should you check collisions? Suppose a basic game with several circles drawn to screen. The user can select and drag any ball and move it around the screen. Should the selected ball overlap with any other ball on screen, the other ball should displace so they are no longer touching. The example I've seen use the following structure for (every ball pair) if (collision true) resolve collision However, with this method, isn't there a risk that a displacement could cause an overlap in a pair already checked, and therefore the overlap printed to the screen? Would it not be better to re check every ball pair's collision, every time a ball is displaced, rather than every time step? Maybe something like for (every ball pair) if (collision true) resolve collision for (every ball pair) if (collision true) resolve collision EDIT Even the method I've listed above shouldn't always provide 100 accurate results. The only way I can think this could work is with some sort of recursive function which only stops when there are no more collisions. Does that seem right?
18
LWJGL Collision Detection I cannot find LWJGL collision detection with a camera and walls. Like making it to where you can not walk through walls and other different shaped rectangular prisms and cubes. How do I set up LWJGL collision?
18
Collision detection a bunch of special cases? I'm writing a simple physics engine in 2D. My first goal is to get collision detection working. I know that my objects will eventually be made up of primitive shapes, but I was wondering would a collision detection library be composed of a bunch of special case functions, like "rayAndLine", "rectangleRectangle", "rectangleCircle" etc, or is there a common, underlying framework for collision detection that works regardless of which primitives are used to make the shape?
18
Navigate multiple Units on a grid through a tight space with different directions I just started learning about pathfinding algorithms. Assume we have this scenario Blue and Green can move only on those tiles. They can also talk to each other. Blue wants to go through the tunnel and green wants to go too, however both need to pass each other somehow. In case of a "basic" A pathfinding algorithm they will both get stuck in the tunnel. To prevent this issue i had some Ideas Blue can tell green that he should move back first (give blue priority) when they both step next to each other (problems arise when there are more than 2) A better algorithm, that calculates this like an automatic traffic regulator (one will wait till the other frees the path) seems complicated Now I am wondering if there are more efficient methods, how its done in general, if you have better ideas, if you can point me to some algorithms or some papers that adress this issue.
18
Collision detection Swinging bat racket and ball I am programming a side view tennis game, inspired by an old arcade game, using Javscript and HTML5 canvas elements. The player can move left and right and holds a racket at arms length which can be rotated 360 degrees around the shoulder joint. I am quite happy with the collision detection and resulting deflection angle between the racket and the ball in the case where the player stands still and the racket does not move. I use a ray casting approach for this collision detection between the vector that represents the racket and the trajectory vector for the ball as proposed here. However, I am having trouble implementing the collision detection between the rotating racket and the ball. When the racket is swung, the area in which a collision would apply has a shape similar to a circular segment , but the racket rotates rotates to fast and the collision detection does not pick it up in most cases. The image bellow illustrates the problem, the red arrow indicates the direction of the swinging racket. The following code snippet from the player entity's update function shows how the racket is updated. arcmx and armcy is the location of the shoulder joint, rstart and rend are the beginning and end of the racket. if(KEY STATUS.rleft KEY STATUS.rright) if(KEY STATUS.rright) this.rangle this.rspeed else if (KEY STATUS.rleft) this.rangle this.rspeed this.armcx this.x this.width 2 this.armcy this.y 46 this.rstartx this.armcx Math.cos(this.rangle) 40 this.rstarty this.armcy Math.sin(this.rangle) 40 this.rendx this.armcx Math.cos(this.rangle) 71 this.rendy this.armcy Math.sin(this.rangle) 71 I am pretty lost on this problem and appreciate any hints on how to approach it.
18
How can I run a Phaser engine game without a window? I'm currently creating a multiplayer game using the HTML5 framework Phaser. It's a game where zombies spawn on the map and players have to shoot them to kill them. The zombies target players that are closest to them. Currently, I'm having my an issue with my design strategy. I'm not sure if this type of game is possible with Phaser due to the movement tracking. At present, the client is handling all of the player movement, so whenever a player moves, it broadcasts it to the server which sends it to all of the other clients. However, I would like for the zombies and the bullets to be controlled by the server exclusively. The server then updates each client with the velocity of each zombie and their current position. My reasoning is that anything that isn't player input should be calculated by the server. This will prevent issues such as two clients saying that a zombie died at different times and then trying to communicate with one another, having bullets at different locations at the same time, or zombies spawning at separate times between clients. Here's an example of a zombie class function Zombie(game, data) this.game game this.id data.id Phaser.Sprite.call(this, this.game, data.x, data.y, 'zombie') this.anchor.setTo(0.5,0.5) this.animations.add('right', 0,1,2,3 , 7, true) this.animations.add('left', 4,5,6,7 , 7, true) this.game.physics.arcade.enable(this) this.body.collideWorldBounds true this.health data.health this.maxHealth data.maxHealth this.speed data.speed this.target this.game.player this.waiting 100 this.name "zombie" this.healthBary 20 this.healthBar this.game.add.sprite(this.x, this.y this.healthBary, 'player health') this.healthBar.anchor.setTo(0.5, 0.5) CollisionManager.addObjectToGroup(this, 'baddies') this.game.add.existing(this) Zombie.prototype Object.create( Phaser.Sprite.prototype ) Zombie.prototype.constructor Zombie Zombie.prototype.update function() this.updateHealthBar() this.moveTowards(this.target) Zombie.prototype.uTarget function(target) this.target target Zombie.prototype.moveTowards function(target) var x target.x this.x var y target.y this.y var mag Math.sqrt((x x) (y y)) var nx x mag var ny y mag this.body.velocity.x nx this.speed this.body.velocity.y ny this.speed if(this.body.velocity.x gt 0) this.animations.play('right') else if(this.body.velocity.x lt 0) this.animations.play('left') Zombie.prototype.updateHealthBar function() this.healthBar.x this.x this.healthBar.y this.y this.healthBary var p (this.health this.maxHealth) p parseFloat(p.toFixed(1)) this.healthBar.frame 10 (p 10) Zombie.prototype. damage function(amount) this.health amount if(this.health lt 0) this.kill this.die(true) Zombie.prototype.die function(points) if(this.game) this.game.baddie die sfx.play() WaveManager.onMap CollisionManager.removeObjectFromGroup(this, "baddies") if(this.healthBar) this.healthBar.destroy() socket.emit("kill zombie", id this.id ) this.kill() this.destroy() The problem is that I can't create a Phaser game object on the server (as it's running on a Linux server) because there's no window that can be used. The bullets and zombies need to be Phaser objects for the sake of collision detection, but I can't do that on the server. I know that I could create a vector of zombies and bullets server side that would have the information for each bullet zombie's position at any given time and then update the client, but then I wouldn't be able to use the CollisionManager in Phaser. Right now, it seems like my only solution is to create my own collision detection system. Are there any alternative ideas?
18
Collision detection against complex shapes and curves I am new in game development and for simple games bounding box collision is fine. However, let's say you have a shape or bitmap like this This is just an example but if you had more elaborate curves or even a whole shape which was more complex than a simple polygon or rectangle like shape, how would you do precise collision detection? I am strictly speaking in 2D here. I just want to know the concept behind how you would do this.
18
What are "distance fields" and how are they applicable to collision detection? I was looking at some efficient methods for collision detection in a scene with both static and dynamic objects when I came across "distance fields." I tried to search and understand this concept, but I could only find papers written in very complex language. Can someone explain in easy words what distance fields are and how can they be used for collision detection?
18
Line Rectangle Collision Detection and Response I've looked through Google and none of the solutions seem to pinpoint my idea. Ultimately, I want to create a level editor where I can draw lines and have them exported to a file for my engine to read. I'm having trouble getting path rectangle to work. I'm using this in the context of a platformer, so I'm also interested in knowing which direction and distance the collision came from so I can resolve it. Which is the best algorithm for doing this? I'm only concerned about axis aligned rectangles. EDIT My character is represented as a rectangle and the level is represented by lines. The tools really do not matter as I'm looking for the mathematics behind it, not necessarily an implementation.
18
Get normal dependent on collisions position As I hask ask here I'm working on how my objects can move over the terrain and other objects. My proposal and also an idea in the answers was to calculate the rotation from the object with the normals from other objects around (under and in front) the moving object. My main problem for that is how I can get the normal from an object at a special position. Let's take the ramp on the road from the old example. It depends from which side my car comes. If it comes from front it can drive along the ramp but if it comes from back it moves against the wall. Of course there are other normals if I come from the other side. All my objects have these variables float vertices float normals short drawOrder float modelMatrix AABBox boundingBox So you see I can allways get the vertices, normals and the position. I can also test if the object collides with another object with the bounding box (axis aligned) but I have no idea how I can get the normal where the collision happens but that is the important thing for the rotation of the car. Do you have any ideas or are there usual way how to do this?
18
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?
18
Collision detection via adjacent tiles sprite too big I have managed to create a collision detection system for my tile based jump'n'run game (written in C SFML), where I check on each update what values the surrounding tiles of the player contain and then I let the player move accordingly (i. e. move left when there is an obstacle on the right side). This works fine when the player sprite is not too big Given a tile size of 5x5 pixels, my solution worked quite fine with a spritesize of 3x4 and 5x5 pixels. My problem is that I actually need the player to be quite gigantic (34x70 pixels given the same tilesize). When I try this, there seems to be an invisible, notably smaller boundingbox where the player collides with obstacles, the player also seems to shake strongly. Here some images to explain what I mean Works Doesn't work Another example of non functioning (the player isn't falling, he stays there in the corner) My code for getting the surrounding tiles looks like this (I removed some parts to make it better readable) std vector lt std map lt std string, int gt gt Game getSurroundingTiles(sf Vector2f position) converting the pixel coordinates to tilemap coordinates sf Vector2u pPos(static cast lt int gt (position.x tileSize.x), static cast lt int gt (position.y tileSize.y)) std vector lt std map lt std string, int gt gt surroundingTiles for(int i 0 i lt 9 i) calculating the relative position of the surrounding tile(s) int c i 3 int r static cast lt int gt (i 3) we subtract 1 to place the player in the middle of the 3x3 grid sf Vector2u tilePos(pPos.x (c 1), pPos.y (r 1)) this tells us what kind of block this tile is int tGid levelMap tilePos.y tilePos.x converts the coords from tile to world coords sf Vector2u tileRect(tilePos.x 5, tilePos.y 5) storing all the information std map lt std string, int gt tileDict tileDict.insert(std make pair("gid", tGid)) tileDict.insert(std make pair("x", tileRect.x)) tileDict.insert(std make pair("y", tileRect.y)) adding the stored information to our vector surroundingTiles.push back(tileDict) I organise the map so that it is arranged like the following 4 1 5 2 3 6 0 7 return surroundingTiles I then check in a loop through the surrounding tiles, if there is a 1 as gid (indicates obstacle) and then check for intersections with that adjacent tile. The problem I just can't overcome is that I think that I need to store the values of all the adjacent tiles and then check for them. How? And may there be a better solution? Any help is appreciated. P.S. My implementation derives from this blog entry, I mostly just translated it from Objective C Cocos2d.
18
How collision boxes are assigned to object in 3D games? Level designers make levels and then programmers import the models and use it but How and when collision boxes are generated for objects and models in the 3D map placed at random locations? Thanks.
18
Should I use Box2D for collision detection only (not simulating physics)? I'm using Box2D only to check collisions and for no physical simulation. I create bodies (and shapes for them) and use my own code to move them, by setting their velocities and positions every frame. I only fetch collision data from the Box2D world. Is this a good idea? For example, can it cause undefined behaviour from Box2D? Is there a more performance friendly way of dealing with different shape collision detections? Do better methods exist for this?
18
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.
18
What is the best way to check for intersection of two bounding boxes, given a minimum and maximum Vector3 for each one I have a BoundingBox object which holds two Vector3's (x, y, z), one for the minimum point and one for the maximum point. ( 1.5 0 9 1.5 3 10) What is the best way to check for any intersection or overlap of two BoundingBoxes? The test for intersection will happen more often than not when there are no points actually intersecting, just faces. The code that I currently am using is bb1.max .x gt bb2.min .x amp amp bb1.min .x lt bb2.max .x amp amp bb1.max .y gt bb2.min .y amp amp bb1.min .y lt bb2.max .y amp amp bb1.max .z gt bb2.min .z amp amp bb1.min .z lt bb2.max .z However this leads to problems when points are, for example 1.5 0 9 1.5 3 10 intersecting with 0.5 0 8.5 0.5 1.8 10.5... The Z minimum and maximum points for the second object laying entirely outside of the Z min and max for the first object.
18
Bounding Box Collision Glitching Problem (Pygame) So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better). Here's the whole code from pygame import DONE False screen display.set mode((1024,768)) class Thing() def init (self,x,y,w,h,s,c) self.x x self.y y self.w w self.h h self.s s self.sur Surface((64,48)) draw.rect(self.sur,c,(self.x,self.y,w,h),1) self.sur.fill(c) def draw(self) screen.blit(self.sur,(self.x,self.y)) def move(self,x) if key.get pressed() K w or key.get pressed() K UP if x 1 self.y self.s else self.y self.s if key.get pressed() K s or key.get pressed() K DOWN if x 1 self.y self.s else self.y self.s if key.get pressed() K a or key.get pressed() K LEFT if x 1 self.x self.s else self.x self.s if key.get pressed() K d or key.get pressed() K RIGHT if x 1 self.x self.s else self.x self.s def warp(self) if self.y lt 48 self.y 768 if self.y gt 768 48 self.y 0 if self.x lt 64 self.x 1024 64 if self.x gt 1024 64 self.x 64 r1 Thing(0,0,64,48,1,(0,255,0)) r2 Thing(6 64,6 48,64,48,1,(255,0,0)) while not DONE screen.fill((0,0,0)) r2.draw() r1.draw() If not intersecting, then moves, else, it moves in the opposite direction. if not ((((r1.x r1.w) gt (r2.x r1.s)) and (r1.x lt ((r2.x r2.w) r1.s))) and (((r1.y r1.h) gt (r2.y r1.s)) and (r1.y lt ((r2.y r2.h) r1.s)))) r1.move(1) else r1.move(0) r1.warp() if key.get pressed() K ESCAPE DONE True for ev in event.get() if ev.type QUIT DONE True display.update() quit() The problem In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast. In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them. The code problem illustrated When the player goes towards the wall (Fine). When the player goes towards the wall and press the opposite direction. (It glitches through). Here is the logic I've designed before implementing it I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching possibilities. What do you suggest?
18
Cocos2d Box2d contact listener call different method in collided object I have the building object, when it collides with another object I want to call some method inside it. Building.mm (void)printTest NSLog( "printTest method work correctly") in my ContactListener I'm trying to call it so ContactListener.mm import "ContactListener.h" import "Building.h" void ContactListener BeginContact(b2Contact contact) b2Body bodyA contact gt GetFixtureA() gt GetBody() b2Body bodyB contact gt GetFixtureB() gt GetBody() Building buildA (Building )bodyA gt GetUserData() Building buildB (Building )bodyB gt GetUserData() if (buildB.tag 1) NSLog( "tag 1") if (buildA.tag 2) NSLog( "tag 2") buildA printTest NSLog( "tag 2") work correctly, but buildA printTest get error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason ' CCSprite printTest unrecognized selector sent to instance 0x18595f0' Obviously I'm referring to the wrong object. How I can get different method and property in contacted objects from contactlistener class?
18
Sliding movement on a grid I'm trying to implement quot sliding quot movement on a simple grid, where the movement vector is continuous (floating point direction) but the grid is discrete (boolean blocked or open on integer axes). The quot destination quot tile is found by adding the rounded movement vector to the current tile. That part is naive and works well enough. For example, here blue is the current (source) tile the yellow arrow is the movement vector green is the destination tile But this movement ends up being restrictive and I'd like to enable quot sliding quot to approximate player intent. My goal is that if the destination tile is blocked, the quot next best quot tile is used instead, provided it is available. I don't know how to calculate that. As you can see, the naive destination tile (where the yellow arrow lands) is blocked. As a result, I'd like to pick the green tile above as the destination tile. However, crossing a diagonal should be allowed either, so the following case should result in the movement being blocked Finally, I'd like this algorithm to be as permissive as possible, so even the smallest component of the movement vector could win if no better alternative is found. For example, the movement should carry upwards in that case This sounds like a fairly simple problem and there may be existing algorithms for it, but I don't know what it's called, so I'm having trouble finding resources on it.
18
Understanding unknown mesh data structure I have a large number of old mesh files in a custom, undocumented binary format. I have managed to parse almost everything but am left with one group of structures, described below, that I don't understand. I hope an experienced graphics programmer can explain what is happening. Here are the structures concerned These types are defined below. We're trying to understand what these three arrays are used to achieve. VertexRef vertexRefs Triangle triangles Unknown unknowns struct VertexRef Earlier in the file, there are several vertex buffers. The file can contain multiple meshes, either as components of a larger mesh, or as multiple LODs. This value group picks out one of these buffers. uint8 t group Index into the vertex buffer picked out by group . uint16 t vertexIndex struct TriangleVertex Index into the array vertexRefs uint16 t vertexRef Index into the array unknowns uint16 t unknownIndex struct Triangle TriangleVertex verts 3 struct Unknown Index into the array vertexRefs uint16 t vertexRef1 Index into the array triangles uint16 t triangleIndex1 Another index into the array vertexRefs uint16 t vertexRef2 triangleIndex2 can be 0xffff, while triangleIndex1 never is uint16 t triangleIndex2 The array of VertexRef is straightforward. It picks vertices, potentially from multiple meshes, to form a composite mesh. The array of Triangle is formed by vertices from the array of VertexRef. Each vertex is also associated with an Unknown. I am out of my depth in understanding what Unknown is doing. Member triangleIndex2 sometimes being 0xffff (or invalid, or nonexistent?) might indicate it is a leaf node of a tree? Perhaps the structure comprising the arrays vertexRefs, triangles and unknowns is some kind of collision detection tree? I'd be very grateful for any hints. Please ask questions if I've failed to be clear enough about something. Edit In answer to a request in comments, I am attaching a sample file and code to load it. The code should run on any likely system. The file is a mesh of a pair of boots. The file is hosted at uploadfiles.io https ufile.io w66mh
18
Isometric 3d collision detection I'm making an isometric map for a game, I can draw it, but I don't know how to implement a sort of 3d collision detection without Threejs or other 3d library. It is possible? Maybe make the block an Object can help? I have searched a lot on the web, but I found only libraries. Thank you! This is my JavaScript code var canvas document.getElementById('canvas'), ctx canvas.getContext('2d'), width canvas.width window.innerWidth, height canvas.height window.innerHeight, stop false var tw, th var player setup() draw() function setup() ctx.translate(width 2,50) tw 60 tile width th 30 tile height player new Player(2,3,2) function draw() ctx.clearRect( width 2, 50,width 1.5,height 50) for(var i 0 i lt 5 i ) for(var j 0 j lt 5 j ) drawBlock(i,j,1,tw,th) if(!stop) requestAnimationFrame(draw) function drawBlock(x,y,z,w,h) var top " eeeeee", right ' cccccc', left ' 999999' ctx.save() ctx.translate((x y) w 2,(x y) h 2) ctx.beginPath() ctx.moveTo(0, z h) ctx.lineTo(w 2,h 2 z h) ctx.lineTo(0,h z h) ctx.lineTo( w 2,h 2 z h) ctx.closePath() ctx.fillStyle "black" ctx.stroke() ctx.fillStyle top ctx.fill() ctx.beginPath() ctx.moveTo( w 2,h 2 z h) ctx.lineTo(0,h z h) ctx.lineTo(0,h) ctx.lineTo(0,h) ctx.lineTo( w 2,h 2) ctx.closePath() ctx.fillStyle "black" ctx.stroke() ctx.fillStyle left ctx.fill() ctx.beginPath() ctx.moveTo(w 2,h 2 z h) ctx.lineTo(0,h z h) ctx.lineTo(0,h) ctx.lineTo(0,h) ctx.lineTo(w 2,h 2) ctx.closePath() ctx.fillStyle "black" ctx.stroke() ctx.fillStyle right ctx.fill() ctx.restore() function drawTile(x,y,stroke,col) ctx.save() ctx.translate((x y) tw 2,(x y) th 2) ctx.beginPath() ctx.moveTo(0,0) ctx.lineTo(tw 2,th 2) ctx.lineTo(0,th) ctx.lineTo( tw 2,th 2) ctx.closePath() if(stroke) ctx.stroke() else ctx.fillStyle col ctx.fill() ctx.restore() function Player(x,y,z) this.x x this.y y this.z z this.w 10 width this.h 10 height canvas width 100 height 100 lt canvas id "canvas" gt lt canvas gt
18
How do I implement a AABB Sphere collision i have been trying to implement an aabb sphere collision. This is what I tried Override public boolean collides(Sphere other) Vector3f axis Vector3f.sub(Vector3f.sub(max, min, null), other.getCenter(), null) float dist axis.length() return dist lt (other.getRadius() other.getRadius())
18
Should your world map have it's own collision object? I am attempting to understand collision detection at the moment. I have seen many examples of a simple flat plane with boxes or cubes which move around on the plane and react when the touch each other (or stop at the plane when dropped). What I am not finding though are more advanced examples where instead of just a flat plane, your map is made up of hills, buildings, walls, etc. Since all of the examples I have found this far use simple primitive collision object types (boxes and spheres), I am curious what the best approach would be for creating a collision object for something like a game map (like dust2 in counter strike). After reading through the bullet documentation I found that you can create a collision object from a triangle mesh, which leads me to believe this might be the best approach. However if your map consists of complex geometry (say hundreds of thousands of verticies and faces), would this be too detailed to use as a collision mesh? Would it then be better to create a separate collision version of the map which is made of simple low poly shapes? My gut is saying "go with the separate low poly version", but if there is no reason for the extra work, it would make more sense to just use the high poly mesh.
18
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.
18
Collision Detection for a 2D RPG First of all, I have done some research on this topic before asking, and I'm asking this question as a mean to get some opinions on this topic, so I don't make a decision only on my own, but taking into account other people's experience as well. I'm starting a 2D online RPG project. I am using SFML for graphics and input and I'm creating a basic game structure and all for the game, creating modules for each part of the game. Well, let me get to the point I just wanted to give you guys some context. I want to decide on how I'm going to work with collision detection. Well I'm kinda going to work on maps with a tile map divided in layers (as usual) and add an extra 2 layers not exactly in the map for objects. So I'll have collisions between objects and agents (players npcs monsters spells etc) and agents and tiles. The seconds one can be easily solved the first one need a little bit of work. I considered both creating a basic collision test engine using polygons and a quadtree to diminish tests since I'm going to be working with big maps with lots of objects creating both a physical and graphical world representation. And I also considered using a physics engine like Box2D for collision tests. I think the first approach would take more work on my part but the second one would have the overhead of using a whole physics engine for just collision detection and no physics. What do you guys think ?
18
Is it possible to have concurrent collision detection where every entity acts at exactly the same time? There are many algorithms that can be used for collision detection. In many cases we check for an overlap in coordinates of an entity. If we make a triangle a,b and c. We have 2 entities at a and b heading for a collision at c but each of them are moving at exactly the same time, what kind of algorithm could work? It seems more like a chess game where you would have to predict every move that the other entity would have to make, if they swerve to the left to avoid a collision will they also run the chance to collide. Is it possible or is it too complex? Would it work for thousands and millions of entities in the same search space?
18
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?
18
Color Based Collision Javascript (Cocos2d js) I'm looking to make an isometric game so my partner designed the isometric map (jpg image) along with the map objects (png) on Adobe Illustrator. The thing is I would like to set the player path based on color, for example if the terrain is white the player can go through, if it's black then the player is not allowed to pass. Is this a viable method to do this or are there better methods? Also I'm using Cocos2D js so my coding is JavaScript I would appreciate any suggestions.
18
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
18
Where should I save game object's attributes (hp, score) in Swift? Scenario I have a game with several game objects on screen. Each can have different score and hitpoints. When I use collision detection for cannonball vs. ship (example) I need to know which ship is hit and how much hitpoints it has. Problem I had several approaches from extending SKSpriteNode or SKPhysicsBody but all failed. SKSpriteNode doesn't work, because Swifts collision detection only returns physicsBody and since you can't extend physicsBody, it didn't work to save there ships attributes as well. Question What would be a good approach to save such data to my game objects? I do not need code because I think I can write it myself but I would be happy to read a good suggestion. But if you have already some code written and a good solution for this problem, I would not be angry to read it )
18
Determine if Plane is seen by Camera If I have an arbitrary plane (center and normal) or a quad (center, normal and width and height) and a camera (frustum, projection amp view matrix, etc). Then how would I go about calculating if the plane quad is visible to the camera? Additionally how would I calculate to check if it's the front or the back of the plane quad that is visible to the camera? My first idea was to do some ray vs plane intersection, but then I realized that it of course wan't going to work! bool plane visible false const float denom plane normal.dot(camera.getLook()) if (abs(denom) gt 0.0001f) const float t (plane position camera.getPosition()).dot(plane normal) denom plane visible (t gt 0.0f) Using the dot product of the plane quads normal and the camera's look direction. Will give wrong results! For instance, use the following image as an example! A dot product will tell me that I'm looking at the face that's facing outwards of the frustum. Though the face that I'm actually looking on is face facing inwards the frustum towards the camera!
18
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?
18
How do I efficiently perform collision detection on an NxN rectangle grid? I have a simple level that is constructed from an NxN rectangle grid. Some of the rectangles are walls, and some of them are the path. The player is allowed to move only on the path they are on and also the path rectangles on the grid. So I have two kinds of rectangles in the grid "path" "wall" The player is a sprite above the grid. I want to efficiently find if the player is colliding with the wall. I want to loop through the rectangles, to see if they intersect. What is the best method?
18
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()
18
How do I determine which voxels to test for collision against the player? I've implemented Minkowski subtraction to test whether (and where) two AABBs collide, independent of framerate time step, in my Minecraft like game. But since there may be tens of thousands of voxels, I'm realizing I can't just test everyone of them. Is there an alternative to just scanning for nearby voxels? I worry that if I just do collision for voxels within a fixed range, then I've undone the framerate independence that I had sought.
18
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.
18
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
18
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)
18
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.
18
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.
18
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.
18
Adding Leniency to Jumping Mechanic I have written some jumping code for my player in a platformer game. At the moment it has some basic logic which says that the player can jump if he is on the ground. The pseudocode looks something like this Input Handling if(jumpButtonPressed) if(onGround) jump Player Update Loop onGround false movePlayer resolveCollisions if(player collided with ground) onGround true This works fine for basic static tile levels, but when the player is standing on a descending platform, or moving down a downward slope for instance, it becomes very difficult to jump. The reason for this (in the case of the descending platform) is that the platform has moved from underneath him in that frame, so for that moment he is not actually colliding with the ground, and therefore the condition to be able to jump is not fulfilled. Is there a general way to add some leniency into the jump mechanic so that the player can jump even if they are not technically on the ground for that exact frame? This seems like it should be quite a common problem but I cannot seem to find any similar questions on stackexchange or google.
18
3D collision detection middleware (I've split this question into two. For 2D, see 2D collision detection middleware) Are there any recommendable middleware available for 3D collision detection? I believe I've heard Bullet has a pretty good 3D collision detection that can be used without the physics engine. I'd like to hear if people have any experiences on Bullet or other libraries for 3D collision detection specifically.
18
Simple (and fast) dices physics I'm programming a throw of 5 dices in Actionscript 3 AwayPhysics (BulletPhysics port). I had a lot of fun tweaking frictions, masses etc. and in the end I found best results with more physics ticks per frame. Currently I use 10 ticks per frame (1 60 s) and it's OK, though I see a difference in plus for 20 ticks. Even though it's only 5 cubes (dices) in a box (or a floor with 3 walls really) I can't simulate 20 ticks in a frame and keep FPS at 60 on a medium aged PC. That's why I decided to precompute frames for animation, finishing it in around 1700 ticks in 2 seconds. The flash player is freezed for these 2 seconds, and I'm afraid that this result will be more of a 5 seconds or even more, if I'll simulate multi threading and compute frames in background of some other heavy processes and CPU drawing (dices is only a part of this game). Because I want both players to see dices roll in same way, I can't compute physics when having free resources, and build a buffer for at least one throw of each type (where type is number of dices thrown). I'm afraid players will see a "preparing dices........." message too often and for too long. I think the only solution to this problem is replacing PhysicsEngine with something simpler, or creating own physicsEngine. Do You have any formulas for cube cube and cube wall collision detection, and for calculating how their angular and linear velocities should change after a collision occurs? Edit I'm assuming the only way to solve my problem is to make a cube cube and cube wall collision engine, however maybe there's another solution for my problem. As Arthur pointer out, there can be one animation for me this is just a shortcut, I could as well show the final result without any dices rolling. However, I thought about making 100 precomputed dice throws, though a user won't avoid repetition here as well. Sometimes a dice sits on it's edge (or corner) for a while, and that gives player some excitement (will it fall on 5 and give me a full house?), but with limited number of animations a player would already know how the animation will end. Buffering solution would work, if players would see dices roll in different way (results would still be the same) I'm considering this solution, however I'm still going to try to create a simple physics engine and see how it works. less ticks is a solution I don't consider, because at as few ticks to be able to simulate physics in real time, the dices behave not better than if I treated them as balls in my physics engine...
18
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.
18
Non rectangular collision detection in Python and Pygame I am programming a ray tracer in python, and I have gotten as far as making a character that can move across a 2d plane and change direction of movement when needed. The problem is this I want to be able to use an image with transparency as the maze that the player travels through, and use transparent parts as parts that aren't walls, where as every thing else is a wall. The way I am using collision detection is by using the quot pygame.sprite.spritecollide quot method, which takes in a Sprite, and a Sprite Group. So I first add the map sprite object to the group, and then in the main while loop, it checks for collision. Here is a small snippet of what that might look like map Map( quot map1.png quot ) quot Map quot class is regular sprite class but with quot image quot and quot rect quot group pygame.sprite.Group() group.add(map) inbetween stuff would be here while loop running True while running event handling stuff would be here if pygame.sprite.spritecollide(player, group, False) print True screen drawing routines would be here As I mentioned, the image has transparency. But never the less, the image rect sticks to the non transparency position that it was, so i have to move the player off screen to get the console to stop saying quot True quot . So what I ask, is there a way that I can check for sprite collision but with transparency?
18
Creating Complex Collision Shapes in GMS2 I'm pretty new to Game Maker Studio 2 and I've hit a wall in programming with their built in physics engine. I created a irregularly shaped object and I want to modify the collision shape so that it fits the shape of the sprite. In the built in collision shape editor it only allows you to create a convex shape with a max of 8 points. Is there another way to do this without having to plot out points individually in code? Thanks!
18
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?
18
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
18
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.
18
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.
18
Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles
18
Collision Detection for a 2D RPG First of all, I have done some research on this topic before asking, and I'm asking this question as a mean to get some opinions on this topic, so I don't make a decision only on my own, but taking into account other people's experience as well. I'm starting a 2D online RPG project. I am using SFML for graphics and input and I'm creating a basic game structure and all for the game, creating modules for each part of the game. Well, let me get to the point I just wanted to give you guys some context. I want to decide on how I'm going to work with collision detection. Well I'm kinda going to work on maps with a tile map divided in layers (as usual) and add an extra 2 layers not exactly in the map for objects. So I'll have collisions between objects and agents (players npcs monsters spells etc) and agents and tiles. The seconds one can be easily solved the first one need a little bit of work. I considered both creating a basic collision test engine using polygons and a quadtree to diminish tests since I'm going to be working with big maps with lots of objects creating both a physical and graphical world representation. And I also considered using a physics engine like Box2D for collision tests. I think the first approach would take more work on my part but the second one would have the overhead of using a whole physics engine for just collision detection and no physics. What do you guys think ?
18
Collision detection circle segment segment I've already implemented collision detection in my game loosely following this tutorial, which works great, but I realized there's one major flaw. The player and the enemies are circles, while the obstacles can be either segments or polygons or circles. Now, let's say I have segment A from point (100, 100) to point (300, 100) and segment B from point (100, 200) to point (300, 100), which means they form an acute angle, and player has it center in point (100, 125), with a radius of 25. If player starts moving right, it will eventually collide against segment B. My method checkCollisions() will return a vector, but if I apply that vector on player, it will be moved up and left, and will overlap segment A. If I call checkCollisions() a second time, player will be pushed down and collide again with segment B, so recursive invocations aren't a solution. Any ideas? Here's a picture to explain The g n vector direction is along the bisector of the two little vectors, but how do I find the length?
18
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?
18
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.
18
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?
18
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?
18
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.
18
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.
18
How will the velocities of two moving objects change once they collide? I'm making a small game where things can fly around and collide. Things like boxes and so on. For each object, I have an array of all forces acting upon it, I have it's mass, it's position and it's velocity in both directions (a 2D vector). I know how to detect collision between them, but I just don't know how to react. I used to calculate their orientation towards each other, it they were on top one another, I would just negate their y speed (v.y v.y), and if they were next to each other on the x axis I would negate their x speed (v.x v.x). Now, this isn't very realistic, so, how do I do it? All objects are rectangles represented by x, y, w, h vectors. Objects can't rotate.
18
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!
18
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?
18
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?
18
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?
18
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.
18
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!)
18
Fast self collision intersection detection algorithm for tetrahedral meshes I want to play with deformation of tetrahedral mesh (soft body simulation) but I need help with self collision detection stuff. I found SOFA collision detection but I'm not sure that it fits for self intersection of a tetrahedral mesh. Can anyone suggest me good algorithm for self collision detection? As far as I can understand, something like BVH of tetrahedra can help me, but it would be great if somebody with expertise shows me right direction.
18
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.
18
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.
18
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.
18
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 )
18
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?
18
Bounding box of a rotated rectangle (2d) I can see this has been asked before in various ways. I am struggling to work it out though hence asking again. 2d sprite that moves and rotates. I'm looking to contain it in a bounding box as it appears that is the most efficient way to do collision detection. I had no problems getting it to work without rotation but that is simple! Now the sprite rotates I can't seem to find the right way of writing the code. To create a bounding box for the sprite, my understanding is I need to work out the 4 corners of the sprite after rotation and use these to work out the width height of the correctly sized bounding box. I've used the article here http msdn.microsoft.com en us library dd162943(v vs.85).aspx specifically the formula x' (x cos A) (y sin A) y' (x sin A) (y cos A) The code I'm currently using x1 (positionX Math.cos(rotation)) (positionY Math.sin(rotation)) y1 (positionX Math.sin(rotation)) (positionY Math.cos(rotation)) x2 (positionX width 2 Math.cos(rotation)) (positionY height 2 Math.sin(rotation)) y2 (positionX width 2 Math.sin(rotation)) (positionY height 2 Math.cos(rotation)) positionX and positionY is the current top left hand corner position of the sprite. rotation is the radians the sprite has been rotated by (and rotation is from the centre). width and height are of the sprite. I thought the code above would give me the co ordinates of the top left and top right corners of the rectangle, rotated appropriately. However, on my canvas, I'm drawing a line from x1,y1 to x2,y2 and it doesn't follow the sprite at all! Any suggestions? Sorry for the long post! Cheers!
18
How to get rid of an image upon collision detection in SDL? I am fairly new to SDL in C, but I have written a simple game whereby a character has to reach the end of a level and avoid bad stars on the way. If he hits a star, he dies. There are also good stars he can collect and get points. I have set up my point system so now when he hits a good star, he should get a point. However, when he hits a star, he actually gets lots of points, as long as he is touching the star, which I don't want. I think that what's happening is because the stars are moving and he rubs up against the stars each pixel he moves counts as a new collision so he gets a point per collision. Ideally, he should only get one point per star. So I have two problems 1) I need to figure out how to make it so that he can only get one point when he hits a star. 2) Since he is supposed to be 'collecting' the stars, I want to make the star disappear when he collects it. So it's similar to most of these types of games, whereby, the player collects something, it disappears and they get a point. EDIT This is struct I've made typedef struct int x, y, w, h, baseX, baseY, mode float phase Goodstar I've then referenced it in another struct like so Goodstar goodStars GOOD STARS SDL Texture goodStar GOOD STARS is equal to 100. And then here's my collision detection code Check for collision with good stars for (int i 0 i lt GOOD STARS i ) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points break So right now it only checks for a collision and then adds a point. EDIT 2 This is the code you suggested and it works for (int i 0 i lt GOOD STARS i ) if (!game gt goodStars i .awarded) if (collide2d(game gt man.x, game gt man.y, game gt goodStars i .x, game gt goodStars i .y, 48, 48, 32, 32)) if (!game gt man.isDead) game gt man.points game gt goodStars i .awarded 1 break And this is my initialisation code Initialise stars for (int i 0 i lt GOOD STARS i ) game gt goodStars i .baseX 320 random() 38400 game gt goodStars i .baseY random() 480 game gt goodStars i .mode random() 2 game gt goodStars i .phase 2 3.14 (random() 360) 360.0f game gt goodStars i .awarded 0
18
Collision resolution when moving in two directions I am making a bomberman clone and I'm having problems regarding moving on both x and y axis (pressing down left, down right, up left). Here is a video to demonstrate the problem. I use Tiled for the map. Below is the code private void checkCollision(float delta) player.getVelocity().scl(delta) dont mind Vector2 position player.getPosition() if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles To reproduce the problem shown in the video Try to collide (coming from up) with one of the blocks that is not on the sides, press both down and left. Try again but press down and right. For the third one, make sure you are colliding with the top wall by pressing up then press left (both are pressed). It can also be done on the bottom wall by pressing down and left.
18
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?
18
Bounding Box Collision Glitching Problem (Pygame) So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better). Here's the whole code from pygame import DONE False screen display.set mode((1024,768)) class Thing() def init (self,x,y,w,h,s,c) self.x x self.y y self.w w self.h h self.s s self.sur Surface((64,48)) draw.rect(self.sur,c,(self.x,self.y,w,h),1) self.sur.fill(c) def draw(self) screen.blit(self.sur,(self.x,self.y)) def move(self,x) if key.get pressed() K w or key.get pressed() K UP if x 1 self.y self.s else self.y self.s if key.get pressed() K s or key.get pressed() K DOWN if x 1 self.y self.s else self.y self.s if key.get pressed() K a or key.get pressed() K LEFT if x 1 self.x self.s else self.x self.s if key.get pressed() K d or key.get pressed() K RIGHT if x 1 self.x self.s else self.x self.s def warp(self) if self.y lt 48 self.y 768 if self.y gt 768 48 self.y 0 if self.x lt 64 self.x 1024 64 if self.x gt 1024 64 self.x 64 r1 Thing(0,0,64,48,1,(0,255,0)) r2 Thing(6 64,6 48,64,48,1,(255,0,0)) while not DONE screen.fill((0,0,0)) r2.draw() r1.draw() If not intersecting, then moves, else, it moves in the opposite direction. if not ((((r1.x r1.w) gt (r2.x r1.s)) and (r1.x lt ((r2.x r2.w) r1.s))) and (((r1.y r1.h) gt (r2.y r1.s)) and (r1.y lt ((r2.y r2.h) r1.s)))) r1.move(1) else r1.move(0) r1.warp() if key.get pressed() K ESCAPE DONE True for ev in event.get() if ev.type QUIT DONE True display.update() quit() The problem In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast. In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them. The code problem illustrated When the player goes towards the wall (Fine). When the player goes towards the wall and press the opposite direction. (It glitches through). Here is the logic I've designed before implementing it I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching possibilities. What do you suggest?
18
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.
18
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?
18
What kind of physics to choose for our arcade 3D MMO? We're creating an action MMO using Three.js (WebGL) with an arcadish feel, and implementing physics for it has been a pain in the butt. Our game has a terrain where the character will walk on, and in the future 3D objects (a house, a tree, etc) that will have collisions. In terms of complexity, the physics engine should be like World of Warcraft. We don't need friction, bouncing behaviour or anything more complex like joints, etc. Just gravity. I have managed to implement terrain physics so far by casting a ray downwards, but it does not take into account possible 3D objects. Note that these 3D objects need to have convex collisions, so our artists create a 3D house and the player can walk inside but can't walk through the walls. How do I implement proper collision detection with 3D objects like in World of Warcraft? Do I need an advanced physics engine? I read about Physijs which looks cool, but I fear that it may be overkill to implement that for our game. Also, how does WoW do it? Do they have a separate raycasting system for the terrain? Or do they treat the terrain like any other convex mesh? A screenshot of our game so far
18
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
18
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 ?
18
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.
18
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)
18
Collision works except for when coming from right side I am trying to make a bomberman clone. I'm having problems with the collision on the walls that is not on the sides of the map (see image). When I come from the right (going left), the red square (player) goes through the wall but when I come from other sides (up, left, down) the collision works well and the player does not go through. The collision on the side walls works well also even when I come from the right and going left. I am using Tiled and LibGDX and here is the code private void checkCollision(float delta) player.getVelocity().scl(delta) Vector2 position player.getPosition() just to see if it overlaps because this is the location of the rectangle when getTiles is called when player moves left as shown in the image Rectangle rect new Rectangle(128, 128, 64, 64) if(player.getRectangle().overlaps(rect)) System.err.println("overlap") if(player.isMovingRight()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap right") player.setPosition(tile.x player.getWidth() , player.getPosition().y) if(player.isMovingLeft()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap left") this doesn't show player.setPosition(tile.x tile.width, player.getPosition().y) if(player.isMovingUp()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap up") player.setPosition(player.getPosition().x, tile.y tile.height) if(player.isMovingDown()) Array lt Rectangle gt tiles getTiles((int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1), (int)(position.x TILE SIZE 1), (int)(position.y TILE SIZE 1)) for (Rectangle tile tiles) if(player.getRectangle().overlaps(tile)) System.out.println("overlap down") player.setPosition(player.getPosition().x, tile.y player.getHeight()) player.getVelocity().scl(1 delta) private Array lt Rectangle gt getTiles(int startX, int startY, int endX, int endY) TiledMapTileLayer layer (TiledMapTileLayer)level.getMap().getLayers().get(1) Array lt Rectangle gt rectangles new Array lt Rectangle gt () for (int x startX x lt endX x ) for (int y startY y lt endY y ) Cell cell layer.getCell(x, y) if(cell ! null) Rectangle rect new Rectangle(x TILE SIZE, y TILE SIZE, TILE SIZE, TILE SIZE) rectangles.add(rect) return rectangles
18
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.
18
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?
18
Collision detection with moving objects I searched a lot about this problem. I found many answers here in Stack Exchange but none of them really answers when positions for objects get updated. For a game with fixed size map and that has all the time 200 moving objects with different sizes (bullets, players, NPCs, etc.) 100 static objects with different sizes (obstacles, health packs, etc.) I am looking for an efficient way to do collision detection. Here is the pseudo code in each game loop (15 ms) collect movement commands and apply force on objects of those commands loop with very small physics time steps (0.1 ms) for object in movingObjects get objects that might collide with current object gt 1 check if any collision occurs for object in movingObjects update position of object (based on command collected) gt 2 So I get the objects that might collide with given object. It is done using a data structure like quadtree or spatial hashing grid (or something else that makes more sense). Object's position is updated. Now, how do I inform the data structure that this object's position is updated? I don't want to remove and insert. That is not efficient at all. I feel like quad tree and spatial hash implementations all over the internet are avoiding this problem. I would also appreciate if you tell me my pseudo code above is problematic. I have the feeling this uses too much CPU.
18
OnTriggerEnter OnTriggerStay triggers multiple times and is not been call a second time I am working on a feature that when the Player pass thru a door, a message will popup on the screen. I'm having few problems Debug.Log gives me from 2 to 6 logs when I pass thru the collider plane and when I come back to the same collider plane the script it is not been call a second time. What I'm trying to achive is that Debug.Log gives me only one log and every time I pass thru the collider the script runs again. so here is my code function OnTriggerEnter (other Collider) OnTriggerStay gives the same result if (other.tag "Player") isColliding true else isColliding false function OnGUI() if (isColliding) Debug.Log(isColliding) Application.ExternalCall('hive.OpenHiveAlert', 'test') function OnTriggerExit() Destroy(this) Any help would be appreciated, thanks.
18
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.
18
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.
18
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.