_id
int64
0
49
text
stringlengths
71
4.19k
18
Create bullet physics rigid body along the vertices of a blender model I am working on my first 3D game, for iphone, and I am using Blender to create models, Cocos3D game engine and Bullet for physics simulation. I am trying to learn the use of physics engine. What I have done I have created a small model in blender which contains a Cube (default blender cube) at the origin and a UVSphere hovering exactly on top of this cube (without touching the cube) I saved the file to get MyModel.blend. Then I used File gt Export gt PVRGeoPOD (.pod .h .cpp) in Blender to export the model to .pod format to use along with Cocos3D. In the coding side, I added necessary bullet files to my Cocos3D template project in XCode. I am also using a bullet objective C wrapper. (void) initializeScene physicsWorld CC3PhysicsWorld alloc init physicsWorld setGravity 0 y 9.8 z 0 Setup camera, lamp etc. .......... ........... Add models created in blender to scene self addContentFromPODFile "MyModel.pod" Create OpenGL ES buffers self createGLBuffers get models CC3MeshNode cubeNode (CC3MeshNode ) self getNodeNamed "Cube" CC3MeshNode sphereNode (CC3MeshNode ) self getNodeNamed "Sphere" Those boring grey colors.. cubeNode setColor ccc3(255, 255, 0) sphereNode setColor ccc3(255, 0, 0) float cVertexData (float )((CC3VertexArrayMesh )cubeNode.mesh).vertexLocations.vertices int cVertexCount (CC3VertexArrayMesh )cubeNode.mesh).vertexLocations.vertexCount btTriangleMesh cTriangleMesh new btTriangleMesh() for (int i 0 i lt cVertexCount 3 i 3) printf(" n f", cVertexData i ) printf(" n f", cVertexData i 1 ) printf(" n f", cVertexData i 2 ) Trying to create a triangle mesh that curresponds the cube in 3D space. int offset 0 for (int i 0 i lt (cVertexCount 3) i ) unsigned int index1 offset unsigned int index2 offset 6 unsigned int index3 offset 12 cTriangleMesh gt addTriangle( btVector3(cVertexData index1 , cVertexData index1 1 , cVertexData index1 2 ), btVector3(cVertexData index2 , cVertexData index2 1 , cVertexData index2 2 ), btVector3(cVertexData index3 , cVertexData index3 1 , cVertexData index3 2 )) offset 18 self releaseRedundantData Create a collision shape from triangle mesh btBvhTriangleMeshShape cTriMeshShape new btBvhTriangleMeshShape(cTriangleMesh,true) btCollisionShape sphereShape new btSphereShape(1) Create physics objects gTriMeshObject physicsWorld createPhysicsObjectTrimesh cubeNode shape cTriMeshShape mass 0 restitution 1.0 position cubeNode.location sphereObject physicsWorld createPhysicsObject sphereNode shape sphereShape mass 1 restitution 0.1 position sphereNode.location sphereObject.rigidBody gt setDamping(0.1,0.8) When I run the sphere and cube shows up fine. I expect the sphere object to fall directly on top of the cube, since I have given it a mass of 1 and the physics world gravity is given as 9.8 in y direction. But What is happening the spere rotates around cube three or times and then just jumps out of the scene. Then I know I have some basic misunderstanding about the whole process. So my question is, how can I create a physics collision shape which corresponds to the shape of a particular mesh model. I may need complex shapes than cube and sphere, but before going into them I want to understand the concepts.
18
From where does the game engines add location of an object? I have started making my first game( a pong game )with ruby (Gosu). I'm trying to detect the collision of two images using their location by comparing the location of the object (a ball) to another one(a player). For example if ( player.x ball.x).abs lt 184 amp amp ( player.y ball.y).abs lt 40 ball.vx ball.vx ball.vy ball.vy But my problem is that with these numbers, the ball collides near the player sometimes, even though the dimensions of the player are correct. So my question is from where does the x values start to count? Is it from the center of gravity of the image or from the beginning of the image? (i.e When you add the image on a specific x,y,z what are these values compared to the image?
18
How should I choose quadtree depth? I'm using a quadtree to prune collision detection pairs in a 2d world. How should I choose to what depth said quadtree is calculated? The world is made mostly of moving objects1, so the cost of dispatching the objects between the quadtree cells matters. What is the relationship between the gain from less collision checking and the loss from more dispatching? How can I strike a balance that performs optimally? 1 To be completely explicit, they are autonomous self replicating cells competing for food sources. This is an attempt to show my pupils predator prey dynamics and genetic evolution at work.
18
Finding the Distance between 2 Objects I have 2 objects One Having a Transformation Matrix T1 and other Having Transformation Matrix T2. And We are having a View Matrix V and Projection Matrix P. Basically 2 Object are render using this function Render(vec3 position,X Rotation , Y Rotation, Z Rotation, Scaling) So i am having 2 different T1 and T2 transformation matrix. How should i find the distance between these 2 objects ? Please Explain ? I have tried by simple formula using position vector but it is giving me incorrect distance ?
18
Super mario bros "rounded" tile collision detection I'm working on a Mario bros clone with SDL and C (purely for educational porpuses and for fun) I got collision detection working by using AABB collision detection and resolving one axis at a time Check collision with X axis first Move entity if not collision is detected Check collision with the Y axis. Move entity if not collision is detected This is working great! However, one thing that I really like about the original Mario bros is that tiles have some kind of "rounded" feel to them. I think this helps make the map feel more organic, see how Mario moves left when jumping on a corner in the original SNES game I thought of using a circle collider for mario instead of an AABB. This would make Mario "fall" off the tiles if you step too close to the edges. But perhaps someone knows a better approach. I've been thinking about collision detection for longer than I'd like to admit. I'd love to know if someone has a clean aproach to accomplish what the GIF shows.
18
How do I create a HeightField in pybullet? I've been looking for documentation on PyBullet, the python implementation of Bullet, but I haven't yet found a way to implement the btHeightfieldTerrainShape collision object, which I need to make, well, terrain. If this isn't possible, is there another way within PyBullet to turn a set of points into a collide able object?
18
How to make sure that when two bodies collide, there is only one collision detection on box2d? I'm using LibGDX with Box2D and, when two bodies collide, the collision is detected multiple times. Here's the code public void preSolve(Contact contact, Manifold oldManifold) Body a contact.getFixtureA().getBody() Body b contact.getFixtureB().getBody() if ((Utils.IsPlayer(a) amp amp Utils.IsEnemy(b)) (Utils.IsEnemy(a) amp amp Utils.bodyIsPlayer(b))) player.isHit true player.destroy() System.out.println(player.isHit) The player is destroyed multiple times I want the player to be destroyed only once.
18
Detect if two objects are going to collide I am working on a car game where I am to create an AI. In the game there are other cars and a few objects moving around that I do not want to crash with, I have the speed, position and direction of all objects including my own car, but how would I go about calculating if my car is on a collision course with another object given my current speed and the other objects current speed? I tried coming up with an algorithm myself but I'm not very good at algebra.
18
Applying statements to a single instance in Game Maker? I'm currently in the process of making a platformer, and am currently in the process of creating "depth" into my game, by making Up Down W S control your depth. (Come closer to screen, go further). The reason I chose to do this is so I can walk around stairs, go behind tables, etc. But I have run into a problem. When I call in my player code, if (depth oWall.depth) code , it is applying to every single wall ever. Is there a way to only make it apply to the object you are currently touching? Here is my code so far Collision TODO Make "depth" apply to a singular instance. if (depth oWall.depth) Colliding with a wall on the Horizontal Axis, causes the player to stop moving. if (place meeting(x h speed, y, oWall)) while(!place meeting(x sign(h speed), y, oWall)) x sign(h speed) h speed 0 Colliding with a wall on the Vertical Axis, causes the player to stop moving. if (place meeting(x, y v speed, oWall)) while(!place meeting(x, y sign(v speed), oWall)) y sign(v speed) v speed 0 Hope you understand what I'm asking.
18
Why does the player fall down when in between platforms? Tile based platformer I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER FRAME event. It's only for collision from the bottom for now. var i int var j int var platform Platform var playerX int player.x 20 var playerY int player.y 20 var xLoopStart int (player.x player.width) 20 var yLoopStart int (player.y player.height) 20 var xLoopEnd int (player.x player.width) 20 var yLoopEnd int (player.y player.height) 20 var vy Number player.vy 20 var hitDirection String for(i yLoopStart i lt yLoopEnd i ) for(j xLoopStart j lt xLoopStart j ) if(platforms i 36 j ! null amp amp platforms i 36 j ! 0) platform platforms i 36 j if(player.hitTestObject(platform) amp amp i gt playerY) hitDirection "bottom" This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.
18
player teleporting into other levels So I basically want to load another map once the player collides with a object, specifically a quot Portal quot in my game. Which is really making the player move onto other levels. I don't want to jumble up my code with a bunch of function like quot go to level 9 quot or something so I'm planning to use a list or dictionary or something. So how to those game devs out there do that? Code for main.py is here https pastebin.com rpddq1MP. The part with the portal stuff, walls and a few others for tile object in self.map.tmxdata.objects obj center vec(tile object.x tile object.width 2, tile object.y tile object.height 2) if tile object.name 'player' self.player Player(self, obj center.x, obj center.y) if tile object.name 'zombie' Mob(self, obj center.x, obj center.y) if tile object.name ' ' Obstacle(self, tile object.x, tile object.y, tile object.width, tile object.height) if tile object.name in 'health', 'shotgun' Item(self, obj center, tile object.name) if tile object.name 'portal' self.map TiledMap(path.join(self.map folder, tile object.type)) how do you do it? I'm currently using Tiled and pygame so I'm also using pytmx. Edit When I run the code, it just gives me an error about my other file, tilemap.py. Error File quot D coding my coding stuff python games pygames little rpg tilemap.py quot , line 49, in apply return entity.rect.move(self.camera.topleft) AttributeError 'TiledMap' object has no attribute 'rect' Tilemap.py import pygame as pg import pytmx from settings import def collide hit rect(one, two) return one.hit rect.colliderect(two.rect) class Map def init (self, filename) self.data with open(filename, 'rt') as f for line in f self.data.append(line.strip()) self.tilewidth len(self.data 0 ) self.tileheight len(self.data) self.width self.tilewidth TILESIZE self.height self.tileheight TILESIZE class TiledMap def init (self, filename) tm pytmx.load pygame(filename, pixelalpha True) self.width tm.width tm.tilewidth self.height tm.height tm.tileheight self.tmxdata tm def render(self, surface) ti self.tmxdata.get tile image by gid for layer in self.tmxdata.visible layers if isinstance(layer, pytmx.TiledTileLayer) for x, y, gid, in layer tile ti(gid) if tile surface.blit(tile, (x self.tmxdata.tilewidth, y self.tmxdata.tileheight)) def make map(self) temp surface pg.Surface((self.width, self.height)) self.render(temp surface) return temp surface class Camera def init (self, width, height) self.camera pg.Rect(0, 0, width, height) self.width width self.height height def apply(self, entity) return entity.rect.move(self.camera.topleft) def apply rect(self, rect) return rect.move(self.camera.topleft) def update(self, target) x target.rect.centerx int(WIDTH 2) y target.rect.centery int(HEIGHT 2) limit scrolling to map size x min(0, x) left y min(0, y) top x max( (self.width WIDTH), x) right y max( (self.height HEIGHT), y) bottom self.camera pg.Rect(x, y, self.width, self.height)
18
Where in code to for collision? In object class? Mainline code? Making a simple game in Love 2D framework where if I click on an object then it disappears. Do I check to see if I've clicked the enemy inside a function in the enemy object? Or just in my main.lua? Currently I have this code in my main.lua function love.mousepressed(x, y, button) if button "l" then for i,b in ipairs(bugs) do if b isClicked(x, y) then table.remove(bugs, i) end end end end Is there a standard design pattern on where this code should belong?
18
Check if a point is touching a user drawn curve in HTML5 canvas I am having trouble detecting whether a ball is colliding with a red curve. The curve below is an example of what a user may draw on to the canvas. I can't think of any fast ways to detect collision between a green ball and the red line here. I have thought of checking the color of the pixel every tick at the location of the ball, but this is very slow and the round ball will fill more than just the centre pixel. I have also thought about logging every single X, Z point that the curve drawer has inserted and then checking if the ball is near to the point, but this also seems like a bad method. From a red curve drawn on to the screen by a user, what is the best way to detect whether a point is colliding with the red line? Shall I store every single point of the red curve or check the color of the pixel at the point to see if it is red or not?
18
Why does my character stop a little before landing on the ground? I made a little game with side scrolling and a box (the player) jumping across the level. The simple physics are almost done, but I have two problem with the way things behave On landing, the box takes a little time to reach the floor When the box hit a roof, there is always a little space between it and the object. Here is my collision code (in the player's Step Event) myGravity 0.5 if (vspeed gt 10) vspeed 10 speedAir abs(vspeed 1) ON FLOOR !(place free(x, y speedAir)) ON AIR place free(x, y speedAir) FREE RIGHT place free(x speedScreen, y) FREE UP place free(x, y speedAir) KEY UP keyboard check(vk up) KEY LEFT keyboard check(vk left) KEY RIGHT keyboard check(vk right) KEY FIRE keyboard check(vk space) JUMP if ON AIR gravity myGravity gravity direction 270 if !(FREE UP) vspeed 0 else if ON FLOOR gravity 0 gravity direction 270 vspeed 0 JUMP if KEY UP amp FREE UP vspeed 10 LATERAL if (FREE RIGHT) x speedScreen screen side scrolling How can I do this correctly?
18
IntersectMovingAABBAABB weird behavior I'm using the IntersectMovingAABBAABB implementation from the book Realtime Collision Detection and I'm having a little bit of an issue. When I have two AABBs next to each other (not touching), A being stationnary and B moving up or down, I'm getting a result saying there's a collision. Obviously this is wrong. A B B moving up down I've rechecked my code multiple times to make sure I had the same thing as in the book. Stepping through the code, I realized that the check for v i lt 0 and v i gt 0 will never be true for either X or Z axis when moving straight up or down. Therefor, no checks for intersections on these axis will be done. I find that quite weird, and I was wondering if I was missing something, or if this code is simply bad. Here's my implementation for reference public static bool IntersectMovingAABBAABB(AABB a, AABB b, Vector3 va, Vector3 vb, out float first, out float last, out BlockFace face) face BlockFace.None if (TestAABB(a, b)) first last 0 return true Vector3 v vb va float current first 0 last 1 for (int i 0 i lt 3 i ) if (v i lt 0) if (b.Max i lt a.Min i ) return false if (a.Max i lt b.Min i ) if ((first Math.Max(current (a.Max i b.Min i ) v i , first)) current) face (BlockFace)(1 lt lt (i)) if (b.Max i gt a.Min i ) last Math.Min((a.Min i b.Max i ) v i , last) if (v i gt 0) if (a.Max i lt b.Min i ) return false if (b.Max i lt a.Min i ) if ((first Math.Max(current (a.Min i b.Max i ) v i , first)) current) face (BlockFace)(1 lt lt (i 3)) if (a.Max i gt b.Min i ) last Math.Min((a.Max i b.Min i ) v i , last) if (first gt last) return false return true
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
Box2d too much for Circle Circle collision detection? I'm using cocos2d to program a game and am using box2d for collision detection. Everything in my game is a circle and for some reason I'm having a problem with some times things are not being detected as a collision when they should be. I'm thinking of rolling up my own collision detection since I don't think it would be too hard. Questions are Would this approach work for collision detection between circles? a. get radius of circle A and circle B. b. get distance of the center of circle A and circle B c. if the distance is greater than or equal to the sum of circle A radius and circle B radius then we have a hit Should box2d be used for such simple collision detection? There are no physics in this game.
18
MonoGame, sprite to rectangle I'm working with MonoGame in VB2015 please don't give answers that involve using C . Anyway, I found a snippet which I converted to VB for pixel collision. The function below accepts two rectangles, then runs a pixel check on the intersection between the two. What I can't work out is how to send my two sprites (textures) to the function as rectangles. Or if anyone has a alternative, please let me know. Private Shared Function IntersectPixels(rectangleA As Rectangle, dataA As Color(), rectangleB As Rectangle, dataB As Color()) As Boolean ' Find the bounds of the rectangle intersection Dim top As Integer Math.Max(rectangleA.Top, rectangleB.Top) Dim bottom As Integer Math.Min(rectangleA.Bottom, rectangleB.Bottom) Dim left As Integer Math.Max(rectangleA.Left, rectangleB.Left) Dim right As Integer Math.Min(rectangleA.Right, rectangleB.Right) (No, this isn't the whole routine...)
18
What's the fastest collision detection (Game Maker) I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10). Each step, I want the cells to check around itself for obj A to see if any obj A is "touching" it, (has a distance less than 10 from the cell). However, since I have so many obj Cell and so many obj A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj A number of obj Cell) In obj Cell (with obj A) if distance to object(other) lt 10 do stuff Is there any possible way to make this faster?
18
How to implement this collision detection function? I would like to know how to implement this collision detection function, but I'm not even sure what it's called. The input shapes are 2D convex polygons, with an optional "rounding radius" imagine putting a circle on each vertex of the polygon, and filling in the area between them. I already have a function that uses SAT to tell if they intersect (and return a minimum correction vector), but I also need a function that takes two of these shapes, A and B, and a unit direction vector. It should tell whether A will ever touch B if it moves along the direction, and if so, report how far it could move and the surface normal where they would touch. So how would that be implemented, or at least how is it called, so I could search for hints?
18
Looking for collision detection algorithms for broad and narrow phases between non convex polyhedrons I have some experiences on particle system simulation (namely DEM Discrete element method), in which an individual particle with realistic shape (convex and non convex) is approximated by gluing 3D spheres together (non overlapping or overlapping), and act like rigid body. The collision detection is performed by the simplest sphere sphere contact. Nevertheless, for particle shape representing by polyhedrons, almost all the collision detection algorithms for broad and narrow phases are based on convex polyhedron (e.g. GJK). For non convex concave shapes, convex decomposition is required to divide the concave object into many convex components (e.g. V HACD). At this point, I really want to know the details on 1) how to store the concave objects via many convex components into memory (like BSP tree?) 2) collision detection and contact forces calculation between convex concave, concave concave objects. I have searched quite a few relevant books like "Real time collision detection" and "3D game engine design", etc, unfortunately I haven't find any details on this topic yet. Could some veteran game developers give some advice or insight on how to implement collision between concave objects? Cheers, David Update 1 Seems the physics engines likes Bullet3 and reactPhysics3D are able to simulate collision of non convex objects. Can someone give some rough idea on how to do this? before I dig into the source codes, since i have only some academic experiences on molecular dynamics DEM simulations mainly based on 3D spheres.
18
Crafty How to get the id of the collision element? As the topic says, I want to know how to get the ID of an active colliding entity. My Player Entity is called with Crafty.e("Player") Please notice, that I do not want the ID of my Player Entity. I want the ID of the Collision element
18
2D destructable terrain with collisions in MMO Task What I want is to create destructable terrain (like in Worms) and collisions with this terrain (with calculated normals) that will be fast enough to work on server machine. Basically lets say that I want to make Worms Online (I don't really) using model CLIENT SERVER, not peer2peer. Approaches I read about People in other threads were suggesting using bitmaps and perpixel collisions, but is it fast enough to handle i.e. 100 games simultaneously? Another approach is using vectors to track outline of terrain, but it seems also really CPU heavy and I didn't find any good example of that. So guys what is your proposal?
18
Multiple collisions within a single frame cycle? So say you want to simulate several objects in two dimensions, just bouncing around in a finite space. Using AABB and sweep tests, it shouldn't be that complicated to calculate single collisions between objects. But if you want to have an object bounce off another surface in the same frame (one collision), how do you account for any additional collisions after that first one? This might not make much sense, so I put a little graphic together to explain what I mean. So say all this is happening in one frame cycle. The gray box moves up and bounces off the wall on the top that's easy enough. That orange box is the problem, though. How do I calculate that collision as well (where the two translucent boxes are)? OR, if the frame rate is high enough, does it even matter? Thanks!
18
How do I detect the intersection of a curve with itself? I'm developing a game in which the player can draw a line. I want to detect if that line intersects with itself. How would I do this?
18
Bitmap Object Collision Help Is it possible to detect when an object and a bitmap collide. I have an arraylist of sprites that I am shooting with an image. I tried using this method here but as soon as the bitmap appears the sprite disappears, this is in the Sprite class public boolean isCollision(Bitmap other) if(other.getWidth() gt x amp amp other.getWidth() lt x width amp amp gt other.getHeight() gt y amp amp other.getHeight() lt y height) return true
18
Shape collision checking I want to check in an shape, wether an point is in it or not. The shape is descriped with one Array of float vectors. The vectors are added in clock direction. The first I can check very easy, the second too, but the third is more difficult. How I can calculate this ? How this category is in math named, so that I can google ?
18
Unity Particle System collision detection problem I'm using Unity 3.5.5f3 wich has the Shuriken particle system. I've made a blood particle system based on Unity's demos. (Exploding paint Blood ) The blood is flowing and when it collides with a Plane Transform wich I've created a small pool of blood spawns as a Collision Sub Emitter. My main problem is that when I want to add another object to collide it just doesn't want to work. When I create a cube, and set it as a collision plane the collision will only occur at the half of the cube. I want this to happen When it reaches the cube's surface the sub emmiter activates, and when the surface is horizontal it appears horizontally, and if it's vertical then vertically. Now it just appears horizontally everytime like in the picture. How could I solve it?
18
If I know a given action will result in a collision, should I allow the action to occur anyway? I've finished programming my game engine, and now that I've been testing it, I've been noticing some graphics problems. The big one is that when a player tries to push against a wall, their character will "jiggle" against it as it constantly tries to enter the wall's space and the collision detection constantly pushes it back outside. What is the proper way to handle such a situation? My first instinct was, if moving in a certain direction causes a collision, disable movement in that direction until the entity's position has changed. I.e., once an object falls onto a platform, disable gravity until the object is no longer above a platform. Is there a better way to resolve repeated collision detections between the same two objects in the same overlapping space?
18
Calculating the intersection of a fast moving circle and a line Inside of my game, I am in need of a way to test the collision between a line segment and a fast moving circle. I would say I need a line v capsule collision however the problem is I need the collision point. None of the existing formulas I can find can do quite what I need. I have tried line x line intersection and just moving the lines by the radius of the capsule sort of work however then the collision point found around the edges is off. Additionally, I can't find a way to work back from the collision point to the point that the circle first collided at. Above is sort of a picture of what I am hoping to achieve. The green capsule represents the circle's path. So really the problem here is finding that collision point because a yes or no answer is trivial here. There are formulas for ray capsule or box capsule however none of them will get me this collision point. Does anyone have any ideas on how I can figure this out?
18
2D Collision in Canvas Balls Overlapping When Velocity is High I am doing a simple experiment in canvas using Javascript in which some balls will be thrown on the screen with some initial velocity and then they will bounce on colliding with each other or with the walls. I managed to do the collision with walls perfectly but now the problem is with the collision with other balls. I am using the following code for it Check collision between two bodies function collides(b1, b2) Find the distance between their mid points var dx b1.x b2.x, dy b1.y b2.y, dist Math.round(Math.sqrt(dx dx dy dy)) Check if it is a collision if(dist lt (b1.r b2.r)) Calculate the angles var angle Math.atan2(dy, dx), sin Math.sin(angle), cos Math.cos(angle) Calculate the old velocity components var v1x b1.vx cos, v2x b2.vx cos, v1y b1.vy sin, v2y b2.vy sin Calculate the new velocity components var vel1x ((b1.m b2.m) (b1.m b2.m)) v1x (2 b2.m (b1.m b2.m)) v2x, vel2x (2 b1.m (b1.m b2.m)) v1x ((b2.m b1.m) (b2.m b1.m)) v2x, vel1y v1y, vel2y v2y Set the new velocities b1.vx vel1x b2.vx vel2x b1.vy vel1y b2.vy vel2y You can see the experiment here. The problem is, some balls overlap each other and stick together while some of them rebound perfectly. I don't know what is causing this issue. Here's my balls object if that matters function Ball() Random Positions this.x 50 Math.random() W this.y 50 Math.random() H Random radii this.r 15 Math.random() 30 this.m this.r Random velocity components this.vx 1 Math.random() 4 this.vy 1 Math.random() 4 Random shade of grey color this.c Math.round(Math.random() 200) this.draw function() ctx.beginPath() ctx.fillStyle "rgb(" this.c ", " this.c ", " this.c ")" ctx.arc(this.x, this.y, this.r, 0, Math.PI 2, false) ctx.fill() ctx.closePath()
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
Collision handling for grid based games and simulations I'm trying to implement a grid based game where there are many creatures moving in the grid from square to square. I'm having a hard time handling collision with creatures in the grid (multiple creatures trying to move into the same square or cell). Where can I find information on how I should handle a game (or simulation) where multiple creatures in a grid want to move into the same cell but aren't allowed to? It's easy to handle 2 creatures, but handling n object collision is tough. I'm looking for info on how to handle collision in a grid world. I don't expect a specific answer as much as resources or suggestions to find more info. EDIT To clarify, I'm looking for info on HOW TO HANDLE COLLISIONS BETWEEN MULTIPLE OBJECTS IN A GRID. In a grid world where multiple objects want to move into the same cell at the same time, how do I resolve this? Does one object get to move into the cell and the other objects remain stationary? Do I make each object push the other object out of its cell? These are the questions I want to answer. An example of the problem I'm looking to answer Consider a grid where there's 3 creatures who move from tile to tile. What do I do when two creatures, A and B, try moving into the same tile? Let's consider if I allow creature A to move into the tile but creature B remains stationary. What happens if a different creature C wanted to move into the tile that creature B was stuck in? Then creature C also wouldn't be able to move. This would cause an issue if I would evaluate creature C's movement first, telling it that he can move into the tile that creature B is in (because creature B plans to move out) but then creature B ends up never moving out. How do I determine which creatures to evaluate first? Also, how do I avoid this huge chain of creatures being forced to remain stationary (in this example, only 1 3 creatures were able to move).
18
Breakout angle calculation I am making my first game in python and I am really stuck at with a physics problem. The game I am trying to make is a copy of the game Breakout. In Breakout, the player controls a "paddle" at the bottom of the screen, which the ball will bounce off of. I have got the collision to work, but I want the angle between the ball's direction vector and the "paddle" to have an impact on the angle at which the ball leaves the paddle. How can I make this work? I have tried a lot of things, but I can't get it to work. In these situations I want the angle to be sharper when the ball hit's closer to the edge of the paddle. How can I calculate and make these angles to work?
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
Bullet impact or force on cube in Blender Hoping someone here may be able to help. I'm new to Blender (and game development 3d modelling) and have been following some tutorials online to get me started. I am building a very basic FPS just to get started. I have a gun that shoots a cube object as a bullet, but when I shoot a different cube object that I added as a target, I have a number of issues. EDIT The target cube is just set as a rigid body object. No other attributes as yet. The cube only moves when I hit one particular face of the cube with a bullet. Otherwise, it doesn't register a hit. It's like the bullet passes right through it unless I hit the particular face. When I hit the correct face, the cube flies way off the screen. I know this is controlled by the physics of each object but I can't find any explanations of it. It's like the box has no weight. If I increase the mass of it, walking against the cube is affected. The cube moves around slower faster depending on the mass, but shooting it shows no change. Could someone give a newbie some pointers?? Thanks so much guys. btw I'm using Blender 2.6 but I reckon that's irrelevant really
18
Separation of axis theorem implementation I have been following the this guide to implement this. My current implementation is the following class SAT SAT() bool collides(Rectangle rect1, Rectangle rect2) var axises rect1.topRight rect1.topLeft, rect1.topRight rect1.bottomRight, rect2.topLeft rect2.bottomLeft, rect2.topLeft rect2.topRight for(var axis in axises) Projection p1 project(axis,rect1) Projection p2 project(axis,rect2) if(!overlap(p1,p2)) return false return true Projection project(Position axis, Rectangle rect) Position projection getProjectionPosition(axis,rect) Collection lt Position gt corners rect.topLeft,rect.topRight,rect.bottomRight,rect.bottomLeft num min dot(projection,corners 0 ) num max min for(var i 1 i lt corners.length i ) num p dot(projection,corners i ) if(p lt min) min p else if(p gt max) max p return new Projection(min,max) bool overlap(Projection p1, Projection p2) return p1.max gt p2.min amp amp p1.min lt p2.max num dot(Position projection, Position point) return projection.x point.x projection.y point.y Position getProjectionPosition(Position axis, Rectangle rect) num p (rect.topRight.x axis.x rect.topRight.y axis.y) (Math.pow(axis.x, 2) Math.pow(axis.y, 2)) Position projected new Position(p axis.x,p axis.y) return projected However this doesn't seem to work. I think I might be a bit confused about the getProjectionPosition algorithm, as you can see I always use rect.topRight. But maybe I am supposed to loop trough all the corners of the rectangle? or should it just be the corner belonging to this axis? The guide wasn't very clear on this. Any ideas on whats wrong? Or is there a reference implementation I could look at to see how my implementation differs?
18
Getting one point collision object to conform to uneven terrain while keeping constant distance covered This is probably best described by image I have a character. For floor collision, it uses a single point (the red X). When the character moves, it conforms to the terrain note how the blue line (its movment per frame) is the same length regardless of the slope. I have the top three situations working fine. The issue is the bottom one, where the character is crossing over a change in slope. I handle the single slope case just by rotating the impending movement vector, but obviously that won't work here. My first instinct was to do something like this Measure length to next vertex along first slope. Subtract length from impending movement vector. Position impending movement vector at vertex rotate to match second slope and get resulting position. Put character at result position. The problem is that it doesn't seem like this will chain very well if the character has to cross over three or more segments at once (maybe it's moving very fast over round like terrain). So basically at this point I'm looking to see if there's an easier solution I'm missing.
18
What is the most efficient way to find hit point of BOX and internal Ray? most efficient AABB vs Ray collision algorithms I found this topic on AABB ray test. Some of them could find hit point of external Ray and BOX. I did my version for both external and internal ray, but it seem not working for internal ray. What's the problem on my solution? Or any good algo for this use case? bool hit(thread Ray amp ray, float2 range t, thread HitRecord amp record) const constant float tmin range t.x float tmax range t.y float3 normal float3(0) for (auto i 0, 1, 2 ) auto min bound (mini i ray.origin i ) ray.direction i auto max bound (maxi i ray.origin i ) ray.direction i auto ts min(max bound, min bound) auto te max(max bound, min bound) tmin max(ts, tmin) tmax min(te, tmax) if (tmax lt tmin) return false if (tmax lt tmin tmax lt 0) return false if (tmax lt tmin tmax lt 0 tmin lt 0) return false if (ts gt tmin) tmin ts normal float3(0) normal i abs(min bound) lt abs(max bound)? 1 1 record.t tmin record.n normal if (tmin lt 0) record.t tmax return true
18
Mesh level acceleration structures for collision detection when mesh instances can be rotated, scaled and or resized Short version in the mid phase or narrow phase of collision detection, does any acceleration structure organizing the mesh's vertices (e.g. AABB trees, Octrees, Quadtrees) work for the mesh's instances that are re scaled, re sizes and or rotated? Long version suppose a concave mesh composed of a very high number of triangles (e.g. 200k) and for which I cannot use convex decomposition in order to perform collision detection. The most efficient solution usually employed would be to organize the vertices of the mesh using acceleration structures to quickly prune which parts of the mesh are likely to have been collided with. However, that mesh is used for generating instantiated copies and each of these can have different size, rotation and or scale at any of the X,Y,Z axis. Would any acceleration structures work since the instances can be re scaled, rotated and resized? Suggestions, tips, academic references, are all appreciated.
18
MonoGame, sprite to rectangle I'm working with MonoGame in VB2015 please don't give answers that involve using C . Anyway, I found a snippet which I converted to VB for pixel collision. The function below accepts two rectangles, then runs a pixel check on the intersection between the two. What I can't work out is how to send my two sprites (textures) to the function as rectangles. Or if anyone has a alternative, please let me know. Private Shared Function IntersectPixels(rectangleA As Rectangle, dataA As Color(), rectangleB As Rectangle, dataB As Color()) As Boolean ' Find the bounds of the rectangle intersection Dim top As Integer Math.Max(rectangleA.Top, rectangleB.Top) Dim bottom As Integer Math.Min(rectangleA.Bottom, rectangleB.Bottom) Dim left As Integer Math.Max(rectangleA.Left, rectangleB.Left) Dim right As Integer Math.Min(rectangleA.Right, rectangleB.Right) (No, this isn't the whole routine...)
18
Determining whether two fast moving objects should be submitted for a collision check I have a basic 2D physics engine running. It's pretty much a particle engine, just uses basic shapes like AABBs and circles, so no rotation is possible. I have CCD implemented that can give accurate TOI for two fast moving objects and everything is working smoothly. My issue now is that i can't figure out how to determine whether two fast moving objects should even be checked against each other in the first place. I'm using a quad tree for spacial partitioning and for each fast moving object, i check it against objects in each cell that it passes. This works fine for determining collision with static geometry, but it means that any other fast moving object that could collide with it, but isn't in any of the cells that are checked, is never considered. The only solution to this i can think of is to either have the cells large enough and cross fingers that this is enough, or to implement some sort of a brute force algorithm. Is there a proper way of dealing with this, maybe somebody solved this issue in an efficient manner. Or maybe there's a better way of partitioning space that accounts for this? Here's a diagram Object A and B's "areas of effect" cross, they should be checked against each other. But with the way i'm currently checking for collisions does not account for this. Again, i can think of a few solutions to this like actually checking if objects' paths cross once their velocity is higher than x, or something, but that feels like a hack and it's a mess to try and implement.
18
3D line segment AABB collision, with hit normal? I'm embarrassed I can't find this, but I'm wanting to detect intersection with a 3D line segment (not an infinite ray) with a 3D AABB, the AABB being defined as two Vec3f's which represent the Min and Max extents. So the AABB can be arbitrarily sized. I also need the surface normal of the AABB, if there was a hit. From looking at similar algorithms I at least know it seems good to calculate the inverse direction of the line beforehand, at least, if you're needing to check against multiple AABBs per frame. I have struct AABB VEC3F min VEC3F max a and b representing start end points of the line segment returns true if intersects, also fills out "normal" if true bool LineIntersectsAABB(const VEC3F amp a, const VEC3F amp b, const VEC3F amp inv dir, const AABB amp aabb, VEC3F normal) The implementations I've found either do not find the hit normal, and or they're intended for boxes cubes where the three dimensions of the box are always equal length, which doesn't work for me. Implementations seem to vary greatly, which is confusing for me (since I'm still trying to learn it), and, considering that I need the hit normal, I'd imagine that that may rule out certain implementations.
18
Determining first voxel ray intersects I'm trying to implement the Fast Voxel Traversal Algorithm on a uniform grid of axis aligned rectangles. Having read the paper, I understand how the traversing works, but not the initialization. I've looked around and I did find a readme that overviews the algorithm, but I fail to see how the derive how to determine the index in a data structure (such as an array) that corresponds to the first voxel the ray intersects. Using the construct presented in the readme, assuming the grid is 2x2 and stored in (going to use Python) an list like so 0, 1 1, 1 0, 0 1, 0 grid (0, 0), (1, 0) , (0, 1), (1, 1) In the overview, the compute r2 r and resolve t 27 32, but I fail to see how they translate that to the index grid 0 . Some other resources I've used to try and understand StackOverflow post Flipcode blog
18
2D collisions between 2 arrays I'm trying to do collision detection between bullets and enemies in my game. But it's very unpredictable and sometimes it works, sometimes it doesn't (bullet goes straight through without doing anything) and sometimes it kills the script returning "Uncaught TypeError Cannot read property 'x' of undefined". The collision detection is just a trivial for loop like this if (enemies.length gt 0 amp amp bullets.length gt 0) for (a 0 a lt bullets.length a ) for (b 0 b lt bullets.length b ) if (bullets a .x 36 gt enemies b .x amp amp bullets a .x lt enemies b .x 56 amp amp bullets a .y gt enemies b .y amp amp bullets a .y 6 lt enemies b .y 69) bullets a .Delete() enemies b .Delete() The .Delete() function is just a reference to arr.splice(index, 1) in the objects. Of course I didn't expect this to be perfect, but I'm surprised by the random behaviour of it. What could cause this and how can I improve the collision detection?
18
How to move towards a point in 2D, stopping at obstacles I want to do a 2D game, where you can mouse click anywhere on the map and the player will go there. If there is obstacle in the way, the player will go as close as possible to where you clicked without going into the non walkable area. What would be the optimal way to accomplish this?
18
How to iterate a sprite group correctly in Pygame avoiding "maximum recursion depth exceeded"? I'm making a game and I have almost finished it, but I'm usually finding the error RuntimeError maximum recursion depth exceeded when I iterate a sprite group. This is an example and the group is self.nextStageCollision() def nextStageCollision(self) for tile in self.nextStageCollision() if tile.rect.colliderect(self.rect) self.rect.x 18 20 self.rect.y 20 20 return True return False The group self.nextStageCollision() has 4 sprites (tiles) and I'm checking collision between my player and those 4 tiles to go to the next stage but I have to be doing something wrong iterating the sprite group because (I don't know why) it becomes recursive and raises the maximum recursion depth runtime error. I've debugged it and when it reaches the for each line, it loops a lot of times there (althought there are only 4 sprites in that group). I know I can increase the recursion depth, but probably it's better to not play with that and try to improve the code. So, what am I doing wrong? Is there another better way to interate a sprite group to check collisions?
18
Prevent camera from moving through walls (no engine or framework) I'm building a fairly basic 3D first person puzzle game. The only objects for which collisions matter are walls, and all walls are at convenient 90 degree angles aligned with the coordinate axes. Unfortunately, I cannot consistently prevent the camera from moving through walls. There is no off the shelf game engine or framework involved, so I have to implement all this from scratch. Currently, my algorithm (in GLSL ish psuedo code) looks something like this void update position(seconds) vec3 ray Raycast(position, speed, map.grid) float xmax max(ray.x .01,0) float ymax max(ray.y .01,0) float zmax max(ray.z .01,0) float dx speed.x seconds float dy speed.y seconds float dz speed.z seconds if(abs(dx) gt xmax) dx (dx gt 0 ? xmax xmax) speed.x 0 if(abs(dy) gt ymax) dy (dy gt 0 ? ymax ymax) speed.y 0 if(abs(dz) gt zmax) dz (dz gt 0 ? zmax zmax) speed.z 0 position.x dx position.y dy position.z dz In prose I cast a ray from the player's camera's current position along the speed vector, which extends until it hits wall. (The Raycast function is used elsewhere, so I already know it works correctly.) I then define the maximum distance the player is permitted to move in each dimension to be slightly less than the component of the ray in that dimension (so that we never end up exactly on a wall). I then compute a provisional set of deltas to add to the current position based on the speed and the time since the last frame (in fractional seconds), and check to see if any of them exceed the maximum allowed magnitude which would take the player through the wall. If they do, I clamp the magnitude of the offending component to its max value, and set the component of speed in that direction to 0 so, the player should end up just barely outside the wall, and sliding along it. This usually works pretty well if you happen to run straight into a wall, but it fails frequently but unpredictably (as in, sometimes it doesn't fail) near corners, and especially near three way corners (where two walls and a ceiling or floor come together). So, what is wrong with this algorithm, and how do I fix it?
18
Platformer movement and collisions I'm working on a platformer but I'm stuck at the player movement and collisions. Right now I'm not including the grid at all in the movement, but it's time I do it. I've read this article on how to do it. But there's no real code examples just theory. I like the second example and that's the one I'm going for. I want the movement to be smooth, and the player should be able to run in between squares from my map array. This means I have to get tile information from the array, and according to that allow forbid my player to move in that direction. And that's where I'm stuck. My array is a bunch of 1's and 0's right now. I know how to calculate a hitbox around the player, but how do I compare that to the array in an efficiant way? UPDATE I've been playing around with this for a while now, and the only thing I came up with is using player X and Y which is in pixels, dividing by tile size, and getting a rough estimate on the map. Then I make it an AABB by adding its width and height to get the corners. This showed to be very unreliable though, and I would really need some help on how to structure this.
18
How do I detect collision between movie clips? I know there are some methods you can use, like hittestPoint and so on, but I want to see where my movie clip collides with another another movie clip. Are there any other methods I can use? I have had trouble finding a good introduction to game physics, and I would like to know how to something like this, properly.
18
Confusing with an articles wording on Clamping a Vector2 I have been reading an article on Collision Detection and how to resolve it. http www.wildbunny.co.uk blog 2011 04 20 collision detection for dummies In the section describing an AABB vs Circle, it states The first step is to get the centre of the circle and project it on to the boundary of the AABB. Fortunately this is as easy as forming the vector V between AABB and circle and simply clamping it against the half extents of the AABB. In the picture provided, it makes sense. You get the vector between the two objects, and then get the closest virtice to the circle and use that in your computation. But, how DO you take the width height into account to that new vector? He says "..simply clamping it against the half extends of the AABB" Can anyone clarify what he means?
18
SAT Collisions Resolving rotations Currently I have a working 2D SAT collision system with only boxes, but works with static rotations as well, leaving room for triangles. One of the issues I've been able to resolve was tunnelling, thanks to this thread's psuedocode that I got working for myself. Problem is, this doesn't support moving rotations like a system using a minimum translation vector. If I rotate alongside the side of an object, the system will fail even if I'm not moving. My first thought in solving this was to use the longest line you can draw in a square (that being the points on either side of a square) and comparing the length of that to whatever side on any axis, but even squares have different sizes on any given rotation projected onto an axis. The system also doesn't work with multiple objects, because while you can use the algorithm on a group of objects and find the shortest distance out of all of them if I conserve my velocity relative to the colliding axis, diving into the crest of 2 objects means I will phase through one of them not beyond a 45 degree angle. Is there an effective way to resolve collisions on rotations and groups of objects, while using this anti tunnelling algorithm? I don't care if it's expensive, I'll take whatever you can think of.
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.
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
Have a simple enemy detecting he touch a wall to make him stop turn around I am doing a very simple scene with a cube sliding on the "ground". Once the cube reach a wall, he is blocked. I want to detect the wall to make the cube go in the other direction. I used OnCollisionEnter but it is triggered at the scene start as my cube touch the ground. I could make a difference between grounds and wall, but my game will make the whole scene rotate, and floor will become wall and wall floor. I wanted to add "physics whatever object" to allow a left right detection but i cannot add collider or rigidbody to my cube. How can i have a cube knowing when he touch a wall without having a false positive with the ground ?
18
Shooting function in pygame w 2 Players I'm trying to program a shooting function in my game using pygame. Process Player one will press 'Space' and shoot their type of projectile Player two would press 'E' and shoot their type of projectile Player one's projectile would collide with player two but not player one (and vice versa). I'm not sure how to code this function properly. Here's my code so far Initalize import pygame, math WHITE (255, 255, 255) Creating sprites class Player(pygame.sprite.Sprite) def init (self, color, width, height) super(). init () Config self.image pygame.Surface( width, height ) self.image.fill(WHITE) self.image.set colorkey(WHITE) Draw pygame.draw.rect(self.image, color, 0, 0, width, height ) Fetch self.rect self.image.get rect() def right(self, pixels) self.rect.x pixels def left(self, pixels) self.rect.x pixels def up(self, pixels) self.rect.y pixels def down(self, pixels) self.rect.y pixels pygame.init() Config RED ( 255, 0, 0) BLUE ( 43, 255, 230) ORANGE ( 255, 170, 0) BLACK (0, 0, 0) SCREENWIDTH 400 SCREENHEIGHT 500 size (SCREENWIDTH, SCREENHEIGHT) screen pygame.display.set mode(size) pygame.display.set caption("Squares Fight") group1 pygame.sprite.Group() player1 Player(BLUE, 50, 50) player2 Player(ORANGE, 50, 50) player1.rect.x 5 player1.rect.y 5 player2.rect.x 345 player2.rect.y 445 group1.add(player1, player2) loop True startend False startanew True clock pygame.time.Clock() font pygame.font.SysFont("berlinsansfb", 72) text font.render("Fight!", True, WHITE) Game Loop while loop for event in pygame.event.get() if event.type pygame.QUIT loop False Logic keys pygame.key.get pressed() if keys pygame.K LEFT player1.left(3) if keys pygame.K RIGHT player1.right(3) if keys pygame.K UP player1.up(3) if keys pygame.K DOWN player1.down(3) if keys pygame.K a player2.left(3) if keys pygame.K d player2.right(3) if keys pygame.K w player2.up(3) if keys pygame.K s player2.down(3) collision pygame.sprite.collide rect(player1, player2) if collision True group1.remove(player1, player2) startend True group1.update() if startend True pygame.display.set caption("They destroyed eachother! Press space to do it again") startanew True if startanew True and keys pygame.K SPACE group1.add(player1, player2) pygame.display.set caption("Squares Fight") startend False Drawing screen.fill(BLACK) screen.blit(text, (200 text.get width() 2, 240 text.get height() 2)) group1.draw(screen) Closing pygame.display.flip() clock.tick(60) Indentation isnt right because how i needed to format this pygame.quit() What else do I need to add to accomplish this task?
18
Collision detected at different times depending on speed? Imagine a scenario where there are four cubes. Two blacks that do not move, one red moving at a constant speed of two (2) straight and the other blue moving at a constant speed of five (5) also straight. They all have equal bounding boxes. By doing a test, I realized that if I put a command so that as soon as the red cube strikes against the black it turns left, the command does not run as soon as they collide ... With the blue he wanted him to turn right as soon as he hit. The command takes longer to happen, I think because it is faster than red ... Illustration of the incident It seems that the faster the object is, the longer it responds to the collision command. I would like you to give me a solution to this problem. I've already moved with some bounding box options, but nothing that has given the desired result. I also moved at the speed of the room, but it did not work either. Sorry for any translation error. Thanks in advance!
18
Unreal Engine 4.18 Knife (Weapon) collides with character capsule collision I have a character and he has a knife in his hand. When Run Walk action happens hands move and so does knife, its collision collides with character's capsule collision and causes issue in movement. More info Component Hierarchy looks like
18
How to create walls and rooms with Pixi I'm a JS dev but pretty new to Pixi and 2D developemnt so please bear with me as I explain this. I want to write a simulator for short path finding (for evacuation purposes). I decided to use Pixi.js for this since it seems capable of doing everything I need to do. I followed this tutorial to try to learn how Pixi works and if its right for this. The tutorial didn't seem to answer many questions I have and I still have some confusion. Before I dive into writing the code, I want to know how wall detection in Pixi acheived. Take the below map for example It is a 800 x 800 png file (where everything but the blue is transparent no grid lines ) that i can load into Pixi as a Sprite. I created it in Tiled editor. So it can be exported as a tilemap, JSON, CSV etc. When I export it as JSON, here is the file contents https pastebin.com zGh1XmR7 The blue boxes represent walls. I want to load in other various sprite objects so that it will look like this The people in the simulations cannot cross the blue walls and they cannot cross the pink circles (they represent danger zones). I intend to use easystar.js to find the shortest path to exits for the people sprites in the map. So my question is this, how does Pixi recognise the blue walls? Is it something I have to do when creating the tileset png? Like something defined in the JSON file for the tileset atlas? Maybe SVG? Or is there a pixi function to do this? Is this the best approach to doing this and is Pixi even the best way to do this? I'm looking for a tried and tested solution or a pointer in the right direction.
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 to optimize collisions I'm building a 2D MORPG using JavaScript, Node JS and socket.io To prevent cheating, I have to run all collisions for all players on my server. I'm currently doing fairly simple square collisions like this for (var i 1 i lt collidables.length i ) if (y lt collidables i .y collidables i .z amp amp x lt collidables i .x collidables i .z amp amp x z gt collidables i .x amp amp y z gt collidables i .y) Handle collision When a player collides with a wall I halve their speed and bounce them back. This is not working optimally, but it's fine for now. The same logic is used to check bullet collision and possibly collision with monsters in the future. I'm currently using 3 different loops for the follwing Player vs Terrain collisions Bullet vs Terrain collisions Bullet vs Monster collisions Since all of them have slightly different logic. Should I put them all in the same loop or is using multiple loops fine? I feel like using multiple loops will slow down my server a lot once there will be some more terrain players monsters. I chose square collisions because I think they are a lot faster than any other type of collision checking, and my game will have a LOT of collision checking. I think I will allow between 50 100 players on a single server, with most likely hundreds of monsters and thousands of bullets flying around. There will also be a rather big map that has to stay loaded on the server. But since the server doesn't actually have to draw anything this should be fine? Client side the map is split up into smaller parts and only loads the parts near the player. My game is working fine for now, but there's no real way to test with 50 players until people actually start playing. I'm afraid I will find out way too late that my collision checking is taking up way too much server memory and or cpu. How can I improve the efficiency of my collision checks? ... Here's a preview of my game in pre alpha, it should make my question less abstract. http 185.115.218.199 3000 If I need to post any more info code, please let me know and I will do so! I'm currently running this game on a very small test server with 512MB RAM and 1 VCPU (can't find the specifications) This is scalable to up to 16GB RAM and 8 VCPU's and probably beyond that.
18
How can I determine the direction of the balls after collision in billiards game? I'm making a billiard game and I have two questions How do I find the velocity of two balls when they collide with each other and how do I apply it to both balls? I already know the angles that they're gonna move, I just need to find the velocity that they'll move in those directions. My game is in 3D, and I'm using Unity. I don't want to use Unity's built in physics to compute the result in this case, I'd like to know how to compute it myself.
18
How can i handle collision response in a voxel game? I'm making a voxel game with cubes like in minecraft and I have figured out how to check wether the player is colliding with a voxel, I have just done it by checking wether the player is within a voxel which is not air, however I don't know how to respond to that i know that the player is inside of a solid cube voxel. Can anyone please suggest how to do it?
18
How to display number of collisions on UI in Unreal Engine using nodes only? I am using Unreal Engine and I want to show on UI the number of collisions using nodes only. How can I achieve that?
18
Collision detection recommendations I am currently developing a prototype game for mobile devices in which the user will see several objects on the screen and will have to touch them one by one in the correct order to win. I guess it that you can say that it is similiar to a Whack a Mole game, but instead of having moles popping up on the screen, I will have several objects moving around. I am having some difficulties in implementing a collision detection algorithm for this game, thefore I would like your recommendation on what is the best method to use. For example suppose an object is moving in a given direction, then I could use the SAT to check if it collides with other objects. If it does collides, then it will stop and move in another direction which is randomly chosen. Another option would be to divide my screen into square or hexagonal tiles. This way I could just check if the tiles are free or occupied before moving the objects. My game be 2D and will use a top down ortographic projection and I am developing it using Cocos2d X and Marmalade SDK. I am not using any physics engine, because my game does not require them (the objects just have to move around, they don't bounce or need any sort of physics behavior).
18
LibGDX Miscalculated polygon collision These 2 polygons are not colliding, though this method returns true Intersector.overlapConvexPolygons( new float 100.0f, 750.0f, 200.0f, 750.0f, 100.0f, 150.0f, 200.0f, 150.0f , new float 77.0f, 695.0f, 91.0f, 695.0f, 84.0f, 681.0f , null) Am I using it correctly?
18
How do I handle my collision resolution using a delegate scheme? My physics engine is coming along quite nicely, and I'm ready to start working on some more advanced features. I'm trying to set up my collision engine so that an arbitrary delegate can be notified when a collision occurs. Say we have object A, object B, and object C in the physics simulation. I want to be able to inform a delegate about a collision between A and B, and also inform a potentially different delegate about a collision between A and C. I have a known interface for the delegate, I have the potential of storing a state for my collision detector, although I currently do not, and have the ability to store states in the objects, themselves. Similarly, I use this delegate model to handle collision resolution, simply setting the physics engine as the delegate for all objects by default, and allowing the user to change the delegate if desired. I have already tried having each object store it's own collision delegate, that would be informed when a collision occurred. This didn't work, because when the objects had the same collision delegate, the same collision was handled twice. When I switched to only using the delegate of the first object (however that was decided), the order of simulation became an issue. I want to use a dictionary, but that introduces a significant amount of overhead. However, that seems like the direction I need to be heading. How do I handle my collision resolution using a delegate scheme?
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
Problem with SAT collision detection overlap checking code I'm trying to implement a script that detects whether two rotated rectangles collide for my game, using SAT (Separating Axis Theorem). I used the method explained in the following article for my implementation in Google Dart. 2D Rotated Rectangle Collision I tried to implement this code into my game. Basically from what I understood was that I have two rectangles, these two rectangles can produce four axis (two per rectangle) by subtracting adjacent corner coordinates. Then all the corners from both rectangles need to be projected onto each axis, then multiplying the coordinates of the projection by the axis coordinates (point.x axis.x point.y axis.y) to make a scalar value and checking whether the range of both the rectangle's projections overlap. When all the axis have overlapping projections, there's a collision. First of all, I'm wondering whether my comprehension about this algorithm is correct. If so I'd like to get some pointers in where my implementation (written in Dart, which is very readable for people comfortable with C syntax) goes wrong. Thanks! EDIT The question has been solved. For those interested in the working implementation Click here
18
Collision detection with non rectangular images I'm creating a game and I need to detect collisions between a character and some parts of the environment. Since my character's frames are taken from a sprite sheet with a transparent background, I'm wondering how I should go about detecting collisions between a wall and my character only if the colliding parts are non transparent in both images. I thought about checking only if part of the rectangle the character is in touches the rectangle a tile is in and comparing the alpha channels, but then I have another choice to make... Either I test every single pixel against every single pixel in the other image and if one is true, I detect a collision. That would be terribly ineficient. The other option would be to keep a x,y position of the leftmost, rightmost, etc. non transparent pixel of each image and compare those instead. The problem with this one might be that, for instance, the character's hand could be above a tile (so it would be in a transparent zone of the tile) but a pixel that is not the rightmost could touch part of the tile without being detected. Another problem would be that in different frames, the rightmost, leftmost, etc. pixels might not be at the same position. Should I not bother with that and just check the collisions on the rectangles? It would be simpler, but I'm afraid people.will feel that there are collisions sometimes that shouldn't happen.
18
Ray box intersection problem I try to implement ray box intersection algorithm given by the following code. However, I'm not really understand for two cases as shown in the following figures. Firstly, when the box is located in front of the ray, why the code give intersection even though the end point of the ray doesn't intersect with the box. A similar observation can be seen from the second case when the ray origin is located inside the box. Is this nature of the algorithm? How can solve this problem? r.dir is unit direction vector of ray dirfrac.x 1.0f r.dir.x dirfrac.y 1.0f r.dir.y lb is the corner of AABB with minimal coordinates left bottom, rt is maximal corner r.org is origin of ray float t1 (lb.x r.org.x) dirfrac.x float t2 (rt.x r.org.x) dirfrac.x float t3 (lb.y r.org.y) dirfrac.y float t4 (rt.y r.org.y) dirfrac.y float tmin max(max(min(t1, t2), min(t3, t4))) float tmax min(min(max(t1, t2), max(t3, t4))) if tmax lt 0, ray (line) is intersecting AABB, but the whole AABB is behind us if (tmax lt 0) t tmax return false if tmin gt tmax, ray doesn't intersect AABB if (tmin gt tmax) t tmax return false if tmin lt 0 then the ray origin is inside of the AABB and tmin is behind the start of the ray so tmax is the first intersection if(tmin lt 0) t tmax else t tmin return true
18
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
detect collision between two circles and sliding them on each other I'm trying to detect collision between two circles like this var circle1 radius 20, x 5, y 5 moving var circle2 radius 12, x 10, y 5 not moving var dx circle1.x circle2.x var dy circle1.y circle2.y var distance Math.sqrt(dx dx dy dy) if (distance lt circle1.radius circle2.radius) collision detected else circle1.x 1 Math.cos(circle1.angle) circle1.y 1 Math.sin(circle1.angle) Now when collision is detected I want to slide the circle1 from on the circle2 (circle1 is moving) like this circle1 circle2 I could do this by updating the angle of circle1 and Moving it toward the new angle when collision is detected. Now My question is that how can I detect whether to update increase the angle or update decrease the angle based on which part of circle2 circle1 is colliding with ?? I would appreciate any help
18
Maintain speed, in 3D game, after collision in Unity I am making a simple breakout game. I have added bounce physics to the ball and to the bricks. When the ball collides with the bricks, the speed of ball slows down. I want ball to maintain its speed to what I set it to intially.
18
2D Tile Collision free movement I'm coding a 3D game for a project using OpenGL and I'm trying to do tile collision on a surface. The surface plane is split into a grid of 64x64 pixels and I can simply check if the (x,y) tile is empty or not. Besides having a grid for collision, there's still free movement inside a tile. For each entity, in the end of the update function I simply increase the position by the velocity pos.x v.x pos.y v.y I already have a collision grid created but my collide function is not great, i'm not sure how to handle it. I can check if the collision occurs but the way I handle is terrible. int leftTile repelBox.x grid gt cellSize int topTile repelBox.y grid gt cellSize int rightTile (repelBox.x repelBox.w) grid gt cellSize int bottomTile (repelBox.y repelBox.h) grid gt cellSize for (int y topTile y lt bottomTile y) for (int x leftTile x lt rightTile x) if (grid gt getCell(x, y) BLOCKED) Rect colBox grid gt getCellRectXY(x, y) Rect xAxis Rect(pos.x 20 2.0f, pos.y 20 4.0f, 20, 10) Rect yAxis Rect(pos.x 20 4.0f, pos.y 20 2.0f, 10, 20) if (colBox.Intersects(xAxis)) v.x 1 if (colBox.Intersects(yAxis)) v.y 1 If instead of reversing the direction I set it to false then when the entity tries to get away from the wall it's still intersecting the tile and gets stuck on that position. EDIT I've worked with Flashpunk and it has a great function for movement and collision called moveBy. Are there any simplified implementations out there so I can check them out? EDIT2 I've figured out a solution, you can check the answer below
18
Collision Scenario, Detection and Response I have AABB, BSphere, a Polygon Soup, a Triangle, a Plane, a Point and a Ray objects with a collision test that returns 'bool' if two objects collide or not. How can I use the above objects to implement an appropriate collision detection for my game? It's a simple game where a player walks inside a rooms, and does the 'escape the room' scenario. My levels is much like old Resident Evil with those 'static' cameras inside the rooms, some items inside containers, a monster and few items laying around so you can pick them up if you want. A room is just a 'Sector' it would be a 'Polygon Soup' A player and all Entities are AABB My question is Is my collision tests that returns (true false) is enough for appropriate collision detection or do I need extra info like the normal vectors? Should I go writing this myself or stop playing around and use some open free physics engine for a simple game like this?
18
How to code a multi level isometric map? I have already worked with isometric grids in the past, but in my current project I found an issue I am not sure on how to solve. I am trying to produce something similar to what's in the below screen What I am having trouble with is how to represent the tiles. With a flat 2d isometric grid all you need is an 2d array (even if you have elevation you can just have a z variable in there to track it and then render based on the z variable plus the z variable of nearby tiles). I am not sure how to proceed with this, however. My plan was to have the map composed of 4 sided polygons that can be placed anywhere, and have a (x, y, z) position. Rendering is easy enough (start with lowest z tiles, go up to the next level, add any stairs that end on that level, keep repeating until all tiles are rendered). However, how can I do collision checking? Checking if a point (a player) is inside the polygon is not too difficult, but how can I know whether he can move to another tile? What would be best Have tiles holding a pointer to neighbouring tiles? (Seems like a lot of trouble to code for the editor). Sort the array by Z level, then search through the array for tiles that are close enough? (Seems slow) Something else entirely?
18
Bullet Apply any Transformation to RigidBody? I'm using Bullet for CollisionDetection. I load a scene from a Collada File using Assimp. Let's say I want to give every object in the scene a RigidBody with a box as CollisionShape. Right now I first load the vertices of the object from the file into my Model Object and then store the transformation matrix. After that I create the CollisionShape with the following code btVector3 rigidBodyPos btCollisionShape collisionShape glm vec3 minMax getMinMaxVertexCoords() glm vec3 minCoords minMax 0 The minmum maximum x y z values in the Mesh glm vec3 maxCoords minMax 1 glm vec3 middleSize glm vec3((maxCoords.x minCoords.x) 2, (maxCoords.y minCoords.y) 2, (maxCoords.z minCoords.z) 2) glm vec3 middlePos glm vec3((maxCoords.x minCoords.x) 2, (maxCoords.y minCoords.y) 2, (maxCoords.z minCoords.z) 2) collisionShape new btBoxShape(btVector3(middleSize.x, middleSize.y, middleSize.z)) rigidBodyPos btVector3(middlePos.x, middlePos.y, middlePos.z) Here's a look at my getMinMaxVertexCoords() glm vec3 Model getMinMaxVertexCoords() float maxValue std numeric limits lt float gt max() float minValue std numeric limits lt float gt lowest() glm vec3 lowestVec glm vec3(maxValue, maxValue, maxValue) glm vec3 highestVec glm vec3(minValue, minValue, minValue) for (Vertex v getVertices()) Apply Transform glm vec4 pos getModelMatrix() glm vec4(v.position, 1) glm vec3 homogenizedPos glm vec3(pos.x pos.w, pos.y pos.w, pos.z pos.w) lowestVec.x min(pos.x, lowestVec.x) lowestVec.y min(pos.y, lowestVec.y) lowestVec.z min(pos.z, lowestVec.z) highestVec.x max(pos.x, highestVec.x) highestVec.y max(pos.y, highestVec.y) highestVec.z max(pos.z, highestVec.z) glm vec3 res 2 lowestVec, highestVec return res The problem doing it this way is, if my scene contains a rotated cube, the collisionbox is obviously not rotated, but parallel to the axes. I tried solving this by applying the transformation matrix only after creating the RigidBody (so when creating the CollisionShape the ModelMatrix is the identity matrix) and then transforming the RigidBody afterwards btTransform transform transform.setFromOpenGLMatrix(glm value ptr(getModelMatrix())) rigidBody gt setWorldTransform(transform) The problem with this however is that the box might be rotated now, but if the transformation contains a Scaling which is very likely Bullet does not accept it, and my RigidBody basically disappears (no collision is detected anymore). Does anybody know a solution to this problem?
18
Subdived objects in different shapes Currently I'm working on an Android OpenGL 3D game and now I want to implement a collision detection. For this I want to use oriented bounding boxes but here is my problem. For a normal oriented bounding box I have to store the middle and then the length into every dimension. Now let's say I have a tree and of course my character can walk under the treetop but not into the tree trunk. I tried to sketch up the different bounding boxes here Tree as two rectangels Normal bounding box x If you think about the collision detection in the first sketch you can walk under the treetop because the border of the tree is subdivided into different shapes and the outline of a tree is still visible. In the second picture you can't tell something about the outline of the object because you only have one big box around the whole object so you can't walk under the treetop. You see the first method is much better then the second method for my plan. Now my question Do you have any ideas how I can subdivide my objects into different shapes? Maybe even in triangles, circles and so on. Is there an algorithm for this or do I have to do it by myself?
18
How to resolve OBB collision penetration? I would think this is a common issue, but I couldn't find an answer that helped me. Help would be appreciated. In my game I have rectangular objects. They have rotating bounding box, aka not AABB but boxes that rotate with the entity and always match it's exact shape (I think it's called OBB). When two objects collide, they often penetrate each other a little My question is, how can I move the objects out of each other? (Before performing the 'actual' collision handling, i.e. setting velocities etc).
18
Rigidbody physics concept Why translate collision shape on the fly instead of mutating it? Crossposting at https stackoverflow.com questions 29993547 rigidbody physics concept why translate collision shape on the fly instead of m I've spent some time going through physics engine's sourcecode in Java like JBox2D, Phys2D (both 2D) and JBullet (3D). I observed that, while the rigid bodies move and are mutated in each step, the collision shapes that are attached to them, are not. Instead, they always stay located around the coordinate origin. When checking two rigidbodies for collisions, a "translation" object is fetched from each and is used to translate the two checked shape's vertices (or other defining properties, depending on the shape type) to their attachment's world position on the fly. These information are then used to detect collisions and react to them. I've concluded the main purpose is, that you can reuse the same shape instance for multiple bodies, as they are stateless in the described scenario and save some memory as the needed information are calculated on the fly in each step. However, I currently see more advantage in mutating the shape's positional properties as in their member values. Each shape's aabb and vertices would change ONE TIME in each step, so you don't need to calculate the same vertices multiple times when intersecting one shape to multiple other ones. Plus, you could also change areal properties (damage deformation) of the shape, because it is only used by one body. So the questions is Why is it common to use positionally immutable collision shapes instead of mutable ones? Edit Found quite the same question, but without much of an answer at Storing rigid body collision shapes in local or world coordinates
18
How can I properly detect my cars collisions using hitboxes? I have created two car objects and their current speed is represented as the len variable. This is the code Under Blue Car Collision Event if (place meeting(x,y,obj CarRed)) Checking Collision len 0 Current speed if (len lt obj carRed.len) Blue Car's current speed is greater than Red's myHP obj carRed.len 2 So I copied the code to the other object and replaced Red with Blue. When the Red car crashes into the Blue car, the Blue car takes damage because the Red car is traveling faster than the Blue car. But when the Blue car crashes into the Red car, the Red car won't take any damage. Later, I thought about using a Hitbox and have it as a parent for both cars, but I don't know if it would mess up the collisions, and I don't know how to tell the hitbox that it's been created by Blue Car, or by Red Car. I don't know if I should make a new hitbox for each car or one for both.
18
How do I make mask work I have been trying to make a game, but mask collision doesn't seem to work. Here is my code class Player(pg.sprite.Sprite) def init (self, game, x, y, lvl) self.group game.all sprites pg.sprite.Sprite. init (self.groups) nothing else important def update(self) self.mask pg.mask.from surface(self.image) check if hits hits pg.sprite.spritecollide(self, self.game.kill, False, pg.sprite.collide mask) if hits stops game self.game.playing False class Kill(pg.sprite.Sprite) def init (self, game, x, y, lvl) self.group game.kill pg.sprite.Sprite. init (self.groups) def update(self) self.mask pg.mask.from surface(self.image) The problem is that the game sets self.game.playing to False even before the pixels collide.
18
How to design Client server hybrid hit detection with projectile weapons? Hybrid hit detection here refers to a architecture where client sends a hit claim to server and server verifies it with a tolerable error limit to confirm the hit or deny it. This technique may work well with hit scan or instant hit weapons because you only have to check it for one frame tick. But in case its a physics projectile I.e where an actual projectile flies to the target like a real bullet, the hit is the result of flight over more than one frames and varying physics state. As such verifying the hit could be very cumbersome and resource intensive. So how would one go for server client hybrid approach in this scenario?
18
Change collision action I have a collision detection and its working fine, the problem is, that whenever my "bird" is hitting a "cloud", the cloud dissapers and i get some points. The same happens for the "sol" which it should, but not with the clouds. How can this be changed ? ive tryed a lot, but can seem to figger it out. Collision Code (void)update (ccTime)dt bird.position ccpAdd(bird.position, skyVelocity) NSMutableArray projectilesToDelete NSMutableArray alloc init for (CCSprite bird in projectiles) bird.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(bird.position.x, bird.position.y, bird boundingBox .size.width, bird boundingBox .size.height) NSMutableArray targetsToDelete NSMutableArray alloc init for (CCSprite cloudSprite in targets) cloudSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(cloudSprite.position.x, cloudSprite.position.y, cloudSprite boundingBox .size.width, cloudSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , cloudSprite boundingBox )) targetsToDelete addObject cloudSprite for (CCSprite solSprite in targets) solSprite.anchorPoint ccp(0, 0) CGRect absoluteBox CGRectMake(solSprite.position.x, solSprite.position.y, solSprite boundingBox .size.width, solSprite boundingBox .size.height) if (CGRectIntersectsRect( bird boundingBox , solSprite boundingBox )) targetsToDelete addObject solSprite score 50 2 scoreLabel setString NSString stringWithFormat " d", score N R SKYEN BLIVER RAMT AF FUGLEN for (CCSprite cloudSprite in targetsToDelete) targets removeObject cloudSprite self removeChild cloudSprite cleanup YES N R SOLEN BLIVER RAMT AF FUGLEN for (CCSprite solSprite in targetsToDelete) targets removeObject solSprite self removeChild solSprite cleanup YES if (targetsToDelete.count gt 0) projectilesToDelete addObject bird targetsToDelete release N R FUGLEN BLIVER RAMT AF ALT ANDET for (CCSprite bird in projectilesToDelete) projectiles removeObject bird self removeChild bird cleanup YES projectilesToDelete release
18
Minimal, unrealistic physics engine I'd like to prototype a game with custom, very simple physics. Something similar to older games, anything from Super Mario to Quake 3 Arena. I'd prefer to avoid realistic physics engine because they usually reduce the control you have over your objects and require you to manipulate such objects in a specific way. I'd want to be able to update the objects' physical state using my own rules. E.g. I'd like to implement and apply gravity, movements and all the rest using my own logic. I believe that what I need is a small engine that handles an efficient representation of objects in a space and offers an interface to query it. I'd also need it to offer decent utilities for very common problems such as collision detection, ray casting, moving overlapping objects away from each other etc. Do similar engines even have a name? They're not considered physics engine, are they? I was planning to work on a 3D prototype, and use JavaScript and Three.js as a language and scene graph renderer. However I might be open to 2D environments and or different technologies. I'd love it if I could find a set of libraries that are meant to work with each other, so that I don't need to write a lot of glue code.
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
Collision Resolution of Axis Aligned Bounding Boxes that Change Size I am developing an action platformer in Python, with Pygame. That said, my question is a general one about collision resolution strategies. I use an axis aligned bounding box for the purposes of collision detection. The bounding box changes sizes depending on the sprite's action and the frame of the action's animation. When I update my sprite's position, I first update the y coordinate, check for and resolve collision in the y direction, then do the same for the x coordinate. When I resolve collision, I simply move the bounding rect's sides to align flush with the appropriate walls. Because the bounding rect changes sizes throughout my animations, I am noticing buggy behavior in certain situations when the frame moves from a smaller one to a larger one. The change of frame results in the sprite intersecting a wall and his position is resolved such that he falls off the map. Here is a diagram illustrating the problem It doesn't matter whether I resolve in the x direction or the y direction first. They result in reciprocal buggy behavior when the next frame is wider or taller, respectively. My question concerns general collision resolution strategies for axis aligned bounding boxes that change size and shape. What are the best algorithms for collision resolution that avoid this issue? Here are some of the functions and values I have access to colliderect tests if two rectangles collide collidepoint boolean that tests if a point collides with a rectangle rect.topleft, rect.topright, rect.bottomleft, rect.bottomright, rect.center, rect.centerx, rect.centery various points on the rectangles rect.left, rect.right, rect.top, rect.bottom values for the sides of the rects various vectors in short, the usual stuff Apologies if this question is a dupe. I imagine it is a pretty common one, though I couldn't find anything that helped me specifically.
18
Collisions with complex assets from Blender in SceneKit I have a very basic workflow question I'm prototyping a game with Apple's SceneKit framework. It can automatically create a mesh for collision detection, but it will always be a convex hull. This works okay for simple meshes, but now I want my character wo walk into a house. The options I could come up with Use the same mesh for the physicsShape (could be too complex and a performance bottleneck) Build the level in SceneKit and only create atomic building blocks in Blender Create a second low poly version of the model and use that for collisions (basically twice the work? As you can see I have zero experience with game development and best practices. What is the typical way to do this?
18
How do I make circles bounce off each other realistically? I'm trying to create bouncing balls with realistic physics. At the moment, when the balls hit each other, they bounce back in the same direction they came from. How do I make them more realistic? I don't know much about physics. What things should I be reading about? Here's an image of how I imagine balls would bounce in real life how I think it should work (original source http thewombatguru.nl Bouncing.png) Is this how it works?
18
Issue with removing sprites on collision I'm trying to make a very simple collision detection procedure just for test purposes. The problem is with the send receive information between functions I have these lines on the update method (could be later implemented for checking what kind of subclass node is) CCSprite sprite background spriteCollisionWithRect player.boundingBox if (sprite! nil) sprite removeFromParentAndCleanup YES and this is the spriteCollisionWithRect method (CCSprite )spriteCollisionWithRect (CGRect)bounds for (CCSprite sprite in spritesArray) if (CGRectIntersectsRect(sprite.boundingBox, bounds)) return sprite return nil Now, this way not all the sprites are removed. It only works occasionally. But if I remove the node inside the collision method instead of returning it, it works nicely. (CCSprite )spriteCollisionWithRect (CGRect)bounds for (CCSprite sprite in spritesArray) if (CGRectIntersectsRect(sprite.boundingBox, bounds)) sprite removeFromParentAndCleanup YES return nil Why is this?
18
How do you set multiple collision rules with Swift and SpriteKit? So basically I've got 2 types of balls and 2 types of enemies. Green can delete red only, red can hit delete only. Here's what I have for the first collision test func didBeginContact(contact SKPhysicsContact) 1. Create local variables for two physics bodies var firstBody SKPhysicsBody var secondBody SKPhysicsBody 2. Assign the two physics bodies so that the one with the lower category is always stored in firstBody if contact.bodyA.categoryBitMask lt contact.bodyB.categoryBitMask firstBody contact.bodyA secondBody contact.bodyB else firstBody contact.bodyB secondBody contact.bodyA 3. react to the contact between ball and bottom if firstBody.categoryBitMask RedBallCategory amp amp secondBody.categoryBitMask GreenBarCategory (secondBody.node!.removeFromParent()) score scoreLabel.text " (score)" This works as expected, red ball hits the green bar and it deletes him. You can't just make a func didBeginContact 2 and change the bit masks as far as I'm aware..or at least it didn't work when I tried it, so how do you handle multiple rules for collision? All of the basic tutorials I've seen handle something like one bullet hitting one type of enemy. What if you have 2 "bullets" and 2 enemies?
18
How can I make player object collide and keep moving until it is as close as possible to click location? I am making a basic point and click adventure game. I can make the player object move towards the location of a mouse click and collide with walls, but movement stops the instant a collision occurs. I would like the player object to keep moving (slide along the wall) and get as close as it can to the mouse click location, without passing through a wall of course. I have Create, Step, Collision amp Global Mouse click events. Please see below for code and diagrams. Any help will be much appreciated. Create Event code stop player moving on create enum mouse none xx mouse.none yy mouse.none player move speed 2 init collision speed player move speed 1 Step Event code general keys if keyboard check pressed(vk escape) game end() point and click movement if (xx ! mouse.none and yy ! mouse.none) move towards point(xx,yy,player move speed) else speed 0 if (distance to point(xx,yy) lt collision speed) xx mouse.none yy mouse.none Global Left Pressed code xx mouse x yy mouse y
18
Detecting a Collision Between Two Bodies Undergoing Multiple Transformations I have been searching for an answer to this for a really long time and I have not found any definitive answers as of yet. What I am trying to do is determine if and when two bodies collided between the times t0 and t1. Calculating this is much more straight forward if each body is only either translating or rotating (about center or any point), but when adding multiple transformations on top of each other, things become a bit more messy. I made this animation to illustrate the problem. As you can see, at times t0 and t1 there are no collisions, but between there are multiple collisions occurring. One way I thought of for tackling this problem was to reduce the size of the time intervals. So, between t0 and t1 there would be a total of n updates to check for collisions. This works, but the only way I found that I could guarantee no false negatives, i.e. not finding a collision that happened, was to integrate over extremely small time steps. As you can imagine, this is very costly because it resulted in the tens to hundreds of time steps per body per update cycle. I am not saying this idea has no merit (it makes calculating the collision response much easier since I know the exact points of contact), but I would need to find a way to calculate the minimum number of time steps rather than uniformly moving each body forward one unit of distance rotation until they reach the desired position and orientation. So, my question is two parts Is there a better way of determining if and when a collision occurs? If not, is it possible to calculate the minimum number of time steps? P.S. I think the maximum translation per time step can be the shortest distance between any two points in the body. This would not allow it to hop over anything. When it comes to rotation about the center or orbiting a point I do not know how to determine the minimum angle. It probably has to do with the arc length, but what should that maximum distance be? EDIT this is not right. For a triangle, the base would be the shortest distance between two of its points, but the top could pass through something that is less wide than the triangle base.
18
SAT Collisions Resolving rotations Currently I have a working 2D SAT collision system with only boxes, but works with static rotations as well, leaving room for triangles. One of the issues I've been able to resolve was tunnelling, thanks to this thread's psuedocode that I got working for myself. Problem is, this doesn't support moving rotations like a system using a minimum translation vector. If I rotate alongside the side of an object, the system will fail even if I'm not moving. My first thought in solving this was to use the longest line you can draw in a square (that being the points on either side of a square) and comparing the length of that to whatever side on any axis, but even squares have different sizes on any given rotation projected onto an axis. The system also doesn't work with multiple objects, because while you can use the algorithm on a group of objects and find the shortest distance out of all of them if I conserve my velocity relative to the colliding axis, diving into the crest of 2 objects means I will phase through one of them not beyond a 45 degree angle. Is there an effective way to resolve collisions on rotations and groups of objects, while using this anti tunnelling algorithm? I don't care if it's expensive, I'll take whatever you can think of.
18
Finding the Distance between 2 Objects I have 2 objects One Having a Transformation Matrix T1 and other Having Transformation Matrix T2. And We are having a View Matrix V and Projection Matrix P. Basically 2 Object are render using this function Render(vec3 position,X Rotation , Y Rotation, Z Rotation, Scaling) So i am having 2 different T1 and T2 transformation matrix. How should i find the distance between these 2 objects ? Please Explain ? I have tried by simple formula using position vector but it is giving me incorrect distance ?
18
Bitmap Object Collision Help Is it possible to detect when an object and a bitmap collide. I have an arraylist of sprites that I am shooting with an image. I tried using this method here but as soon as the bitmap appears the sprite disappears, this is in the Sprite class public boolean isCollision(Bitmap other) if(other.getWidth() gt x amp amp other.getWidth() lt x width amp amp gt other.getHeight() gt y amp amp other.getHeight() lt y height) return true
18
What are the disadvantages of R Trees in collision detection? I was poking around in SQLite and discovered R trees. A little digging revealed that R trees are really just fancy AABB trees. Then I realize that the state of the art in collision detection (often a perf limiting sub system for physics simulation) is dynamic trees (simple AABB trees). So this is indicating to me that we can produce more efficient physics with this as a drop in replacement. Here is a pretty convincing argument for R trees from half a decade ago. To really distill it to the core, R trees were developed for databases to optimize disk access where getting the right data into RAM is the happy place, and now we can recycle the technique to optimize memory access where keeping the right data in cache is the happy place. Sadly it seems that this has not caught on. I wonder what the reasons are? I also found no reference to this BVH method in my Real Time Collision Detection (Ericson) text (though, that book is a bit older than 2010).
18
Explain Reciprocal Velocity Objects to me This is follow up on this question (Unit collision avoidance for RTS) I'm developing an RTS. I'm having difficulty with collision detection... I looked up RVO and it seems like the correct solution, but I'm having difficulty understanding how it exactly works. Can someone explain the math behind RVO in comprehensible terms? I tried compiling the RVO sample program but it won't compile in the latest version of Visual Studio. I'm stumped.
18
Collision detection of player larger than clipping tile I want to know how to check for collisions efficiently in case where the player's box is larger than a map tile. On the left is my usual case where I make 8 checks against every surrounding tile, but with the right one it would be much more inefficient. (picture of two cases on the left is the simple case, on the right is the one I need help with) How should I handle the right case?