简体   繁体   中英

How to detect collision to stay within box

So how would I be able to keep the green rectangle from getting outside of the box I have provided? If possible without using any classes. I would like to make a small map for levels within the given window so is there any way I can keep the rectangle from slipping through the lines? Or is it possible to force the rectangle to stop moving after hitting a certain point?

import pygame

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)

#Functions
def drawSquare(screen, x, y):
    pygame.draw.rect(screen, BLACK, [x, y, 21, 21])
    pygame.draw.rect(screen, GREEN, [3+x, 3+y, 15, 15])

def drawMap():
    pygame.draw.rect(screen, BLACK, [0, 1, 100, 100],5)
pygame.init()

# Set the width and height of the screen [width, height]
size = (800, 600)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()
#Loading pictures

#Variables
# Speed in pixels per frame
x_speed = 0
y_speed = 0

# Current position
x_coord = 10
y_coord = 10
# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop

        elif event.type == pygame.KEYDOWN:
            # Figure out if it was an arrow key. If so
            # adjust speed.
            if event.key == pygame.K_LEFT:
                x_speed = -3
            elif event.key == pygame.K_RIGHT:
                x_speed = 3
                if x_coord > 200:
                    x_speed = 0
            elif event.key == pygame.K_UP:
                y_speed = -3
            elif event.key == pygame.K_DOWN:
                y_speed = 3
        elif event.type == pygame.KEYUP:
            # If it is an arrow key, reset vector back to zero
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_speed = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_speed = 0



    x_coord = x_coord + x_speed
    y_coord = y_coord + y_speed

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.


    # --- Drawing code should go here
    screen.fill(WHITE)
    drawSquare(screen, x_coord, y_coord)
    drawMap()

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(45)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

If I understand your question, you want to keep the square you are drawing within the view bounds. I think this will do it for you (the top two lines are already in your code above, just to show where this would go).

x_coord = x_coord + x_speed
y_coord = y_coord + y_speed

# consider moving these to the top and using them in your drawMap function
map_x = 0
map_y = 1
map_width = 100
map_height = 100

x_coord = max(map_x, x_coord)
y_coord = max(map_y, y_coord)

# coordinates must be less than size of container 
# the 21 here is the size of the square you are drawing
# consider making it a variable rather than hard coded number
x_coord = min(x_coord, map_width - 21) 
y_coord = min(y_coord, map_heigh - 21)

While I think if you keep on this course (avoiding using classes/using global variables) you will find your code will become unmaintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM