# Is this inefficient?

So, I’ve been trying to figure out how to do collisions, and while what I got works, I’m afraid it may be a bit inefficient.

So, I have a function called `PlaceMeeting` and when my `Update` of my game objects gets called, it will detect some input and moves, and then check for collisions.

It detects collisions by checking on the x-axis, and if it’s about to collide, it will loop until it is ~1 pixel away from the object, and the sets the velocity to zero. It’s the same for the y-axis.

What I’m concered about is how in the `PlaceMeeting` function it does a loops through a list of objects with a `foreach` loop, and then checks collisions. It does this every time it’s called.

I’m worried this may be inefficient, and could cause lag when my game starts getting bigger. Is this gonna be a problem, or will it be fine if I leave it as it is?

I did something like that at first for the game I was making (granted it was for triangular collision) but after I placed like 100 blocks in a level and had countless enemies it really started to hamper performance.

I’d recommend waiting to detect a collision (with an AABB) and then determine which direction of the intersected box your on (by checking your sprites XY position) and then move your sprites position to just the border of where the collision took place; this is what I changed mine to do.

you would like to use Quadtree vs Spatial Hash (…) to reduce potential objects

I strongly recommend using a spatial hash. It’s very easy to implement and pretty much always good enough (most of the time even better than a quadtree) for 2D stuff. Basically you put all your entities into a grid of squares (or rectangles) and when checking collision for say entity A, only check other entities B that touch a square that entity A touches. If you don’t want to implement your own, there are multiple open-source implementations available. For example MonoGame.Extended implements this in their Collisions namespace as a CollisionGrid: https://github.com/craftworkgames/MonoGame.Extended/blob/develop/Source/MonoGame.Extended.Collisions/CollisionGrid.cs