Как мне поменять хитбокс одного из моих спрайтов? - PullRequest
1 голос
/ 21 июня 2019

Так что, когда игра начнется, у пользователя появятся ящики для уклонения, но в настоящее время хитбоксы объектов немного отключены ... например, когда вы перемещаете корабль через поле, он регистрируется как удар, заканчивающийся на игра окончена.

Это для задачи по оценке проектирования и разработки ПО HSC. Я не совсем уверен, что делать, чтобы решить эту проблему

Вот код!

#This program was created by Tadiwa Mooyo
#more of the car game has been worked on, now there are boxes for the user to "dodge" and it will display the crash message when the boxes are hit
#This program was started on the 22/02/2019
import pygame
import time
import random

pygame.init()

display_width = 1200
display_height = 700
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

car_width = 100

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('The Great Space Escape!')
clock = pygame.time.Clock()
carImg = pygame.image.load('Ships_directory\\Green_black_ship.png')

def things_dodged(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Score: "+str(count), True, white)
    gameDisplay.blit(text,(0,0))


def things(thingx, thingy, thingw, thingh, color):
    pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])

def car(x,y):
    gameDisplay.blit(carImg,(x,y))

def text_objects(text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()

def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    gameDisplay.blit(TextSurf, TextRect)

    pygame.display.update()

    time.sleep(2)

    game_loop()



def crash():
    message_display("You Crashed")

def game_intro():

    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        gameDisplay.fill(black)
        largeText = pygame.font.Font('freesansbold.ttf',115)
        TextSurf, TextRect = text_objects("A bit Racey", largeText)
        TextRect.center = ((display_width/2),(display_height/2))
        gameDisplay.blit(TextSurf, TextRect)
        pygame.display.update()
        clock.tick(15)




def game_loop():
    x = (display_width * 0.45)
    y = (display_height * 0.5)

    x_change = 0

    thing_startx = random.randrange(0, display_width)
    thing_starty = -600
    thing_speed = 4
    thing_width = 200
    thing_height = 200

    dodged = 0

    gameExit = False

    while not gameExit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -10
                if event.key ==pygame.K_RIGHT:
                    x_change = 10

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        x += x_change

        gameDisplay.fill(black)


        #things(thingx, thingy, thingw, thingh, color)
        things(thing_startx, thing_starty, thing_width, thing_height, white)
        thing_starty += thing_speed
        car(x,y)
        things_dodged(dodged)

        if x > display_width - car_width or x < 0:
            crash()

        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0,display_width)
            dodged += 1
            thing_speed += 0.5
            thing_width += (dodged * 1.4)        

        if y < thing_starty+thing_height:
            print('y crossover')

            if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
                print('x crossover')
                crash()


        pygame.display.update()
        clock.tick(60)

game_loop()
pygame.quit()
quit()

1 Ответ

1 голос
/ 21 июня 2019

Используйте pygame.Rect, чтобы упростить ваш код и выполнить тест на столкновение с помощью .colliderect():

, например

things_rect = pygame.Rect(thing_startx, thing_starty, thing_width, thing_height)
car_rect    = pygame.Rect(x, y, *carImg.get_size())

if car_rect.colliderect(things_rect):
    crash()

Если вы хотите реализовать свой «собственный» тест, который проверяет, пересекаются ли 2 прямоугольника, вы должны проверить, перекрывают ли прямоугольники в обоих измерениях.

2 диапазона [x1, x1+w1] и [x2, x2+w2] перекрываются, если x1 < x2+w2 and x2 < x1+w1.

Таким образом, тест пересечения для прямоугольников можно выполнить следующим образом:

car_w, car_h = carImg.get_size()
if (thing_startx < x+car_w and x < thing_startx+thing_width and 
    thing_starty < y+car_h and y < thing_starty+thing_height):
    crash() 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...