0

I am trying to code the section of a game which will handle the collision detection. Currently it looks like this

def collision_detection(player_x, player_y):
movment_ok=1
cannot_go_onto=[[0,20,20,40],[520,500,480,460]] #coordinates with no access. X, Y
if player_x in cannot_go_onto[0]:
    location_in_array=cannot_go_onto[0].index(int(player_x))
    if player_y==cannot_go_onto[1][location_in_array]:
        print("collision detection")
        movment_ok=0
return movment_ok

This works fine for the coordinates (0,520),(20,500) & (40,460) however it doesn't work for the coordinate (20,480). I think this is because of the line

location_in_array=cannot_go_onto[0].index(int(player_x))

The index search is returning 1 because it simply takes the first time 20 appears in the array twice. Therefore only the position (20,500) is checked as it appears first in the array. However I don't know how to fix this problem. Any ideas/help would be hugely appreciated.

1 Answer 1

4

Wouldn't it be simpler to just have an array of the no access coordinates, instead of 2 seperate lists.

cannot_go_onto = set([(0,520), (20,500), (20,480), (40,460)])

def collision_detection(player_x, player_y):
    play_position = (player_x, player_y)
    if play_position in cannot_go_onto:
        print("collision detection")
        return False
    return True

Edit:

  • Placed cannot_go_onto outside the function because there is no need to recreate the array everytime.
  • Made cannot_go_onto a set, which is better for searching performances. (Thanks tobias_k for pointing it out)
Sign up to request clarification or add additional context in comments.

2 Comments

Might also make cannot_go_onto a set, and global.
Thank you for this, works perfectly now. Il accept your answer when the timer runs out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.