Home > Enterprise >  How would you pass an If statement WHEN 2 coordinate arrays are within a range of 10 of each other?
How would you pass an If statement WHEN 2 coordinate arrays are within a range of 10 of each other?

Time:09-22

I am using Pygame for a programming class and need to recreate a game of tag. I am attempting to pass an if statement when the coordinates of the tagger are within a range of 10 of the player's coordinates. I attempted using 'in range()' within the if statement but it didn't seem to work. Not sure what I was doing wrong.

if (pos[0] == enemypos[0] & pos[1] == enemypos[1]):

    font = pygame.font.SysFont('Calibri', 25, True, False)

    gameovertext = font.render("You're IT", True, WHITE)

    screen.blit(gameovertext, [x_mouse 10, y_mouse 10])

CodePudding user response:

If you subtract the two sets of coordinates from each other, then you will get the difference between them. This value could be negative, so you would also need to use abs(on the values)

if (abs(pos[0] - enemypos[0]) <= 10 and abs(pos[1] - enemypos[1]) <= 10:

CodePudding user response:

Subtract them to get the difference in position, rather than checking equality:

if abs(pos[0] - enempypos[0]) < 10 and abs(pos[1] - enempypos[1]) < 10:

You can also compute the Euclidean distance.

CodePudding user response:

You can use the dist function in the standard math library to caculate the euclidean distance.

import dist from math

if dist(pos, enemypos) >= 10:
  # in range
  • Related