Skip to content

Instantly share code, notes, and snippets.

@Arxcis
Created December 9, 2016 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arxcis/aa2693cf4c5f9fd890f3021bff4b613e to your computer and use it in GitHub Desktop.
Save Arxcis/aa2693cf4c5f9fd890f3021bff4b613e to your computer and use it in GitHub Desktop.
# 09.12.2016 - Jonas
# Trying to make an efficient collision detection
import random
import math
from . import Blob
widtH = 800
heighT = 600
no_of_blobS = 30
runninG = True
grid_resO = 10 # Grid resolution
# ------------------- INITIALIZING -----------------------------
# Making a grid, 10th the size of the screen
# each block containing an empty dict (bucket)
blob_grid = [[ {} for i in range(widtH/grid_resO) ] for i in range(heighT/grid_resO) ]
# Initing blobs
# at a random location on the screen
blobs = [ Blob( random.randrange(0, widtH ), # Blob( x, y, type, size)
random.randrange(0, heighT ),
random.randrange(0, 3 ),
random.randrange(1, 5 )) for i in range(no_of_blobS)] # no_of_blobS = number of blobs
for blob in blobs: # Filling a reference each blob into their respective 'bucket'
blob_grid[ blob.x/grid_resO, blob.y/grid_resO ][id(blob)] = blob # id(object) gives unique id
# -------------------- GAME LOOP ------------------------------
while runninG:
# Update Blob position and detect collision
for blob in blobs:
del blob_grid [blob.x/grid_resO, blob.y/grid_resO][id(blob)] # Remove blob from current block in the grid
blob.move() # Moving blob to a new position x, ys
blob_grid [blob.x/grid_resO, blob.y/grid_resO][id(blob)] = blob # Insert blob at new grid location
for i in range(3): # Loop through the 3x3 grid surrounding the blob in question
for k in range(3): # Loop through all blobs in a grid block
for other_ID, other_blob in blob_grid[blob.x/grid_resO-1 + k, blob.y/grid_resO-1 + i]:
# Check other blobs id and type
if other_ID == id(blob) or other_blob.typ == "blue":
pass
else: # If distance between blobs is less than the sum of radius
if math.sqrt(pow(other_blob.x-blob.x) +
pow(other_blob.y-blob.y)) < blob.size + other_blob.size:
blob + other_blob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment