2015-01-02 6 views
0

나는 최근에이 코드를 작성해 왔으며 충돌 감지를 원했지만 이전에는 해본 적이 없으며 도움이 필요하다. 이 코드는 간단해야한다, 그래서 파이썬과 파이 게임으로 작성하지만 난파이 게임에서 어떻게 충돌 탐지를합니까?

import pygame, os, itertools 
from pygame.locals import * 

w = 640 
h = 480 
pink = (0,179,179) 
player_x = 39 
player_y = 320 

def setup_background(): 
    screen.fill((pink)) 
    screen.blit(playerImg, (player_x,player_y)) 
    screen.blit(brick_tile, (0,0)) 
    pygame.display.flip() 

pygame.init() 
screen = pygame.display.set_mode((w, h)) 
clock = pygame.time.Clock() 
playerImg = pygame.image.load('img/player.png').convert_alpha() 
brick_tile = pygame.image.load('img/map.png').convert_alpha() 

class Player(pygame.sprite.Sprite): 
    allsprites = pygame.sprite.Group() 
    def __init__(self): 
     pygame.sprite.Sprite.__init__(self) 

     self.image = pygame.image.load('img/player.png') 
     self.rect = self.image.get_rect() 

class World(pygame.sprite.Sprite): 
    allsprites = pygame.sprite.Group() 
    def __init__(self): 
     pygame.sprite.Sprite.__init__(self) 

     self.image = pygame.image.load('img/map.png') 
     self.rect = self.image.get_rect() 

player = Player() 
world = World() 
done = False 
while not done: 
    setup_background() 
    block_hit_list = pygame.sprite.spritecollide(player, world.allsprites, True) 

    for world in block_hit_list: 
     print("WORKING") 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      done = True 
     if event.type == pygame.KEYDOWN: 
      if event.key == K_RIGHT: 
       player_x += 5 
+0

스프라이트 검출 방법을 알고 싶습니까? 세계가 투명해야하는지에 대한 의견이 필요합니까? –

답변

0

스프라이트 충돌 감지가 거의하지만 잘못 투명한 이미지로 온 세상을해야하는지 모르겠어요된다. 이 줄의이 개념의 기본 사항을 알고있는 것 같습니다.

block_hit_list = pygame.sprite.spritecollide(player, world.allsprites, True) 

거의 다 왔지만, 여기에 나와 있습니다. pygame.sprite.spritecollide() 함수에서 스프라이트의 이름, 그룹의 다른 스프라이트의 이름, True 또는 False이 필요합니다. 귀하의 경우에는, 당신은 (당신이 순서대로 일을 원하는 가정) 당신의 세계에 대한 그룹을 만들 필요가 :

world_group = pygame.sprite.Group(world) 

이 줄이 감지 코드에 대한 필요하며, 제거 할 것을 스프라이트를 가능하게 할 것이다. 해당 그룹에 또 다른 세계를 추가 할, 그래서 당신은 세계의 많은이있는 경우,이 작업을 수행하고 당신이 원하는 경우 주위 몇 코드를 추가

world_group.add(world) 

add() 기능은 해당 그룹에 스프라이트를 추가합니다. 필요한 경우 루프를 만들어서 많이 만들 것을 권장합니다. 이제 충돌 코드!
이제이 기능을 올바르게 수행 할 준비가되었습니다. 먼저이 줄을 삭제합니다.

block_hit_list = pygame.sprite.spritecollide(player, world.allsprites, True) 

지금은 불필요하고 쓸모가 없습니다. 당신은 당신의 루프의 while 루프하지만 외부에서이 if 문을 추가해야합니다

if pygame.sprite.spritecollide(player, world_group, x): 
    #Do something 

왜 내가 대신 True 또는 Falsex이 있었습니까? 그게 당신의 결정 일거야. 연락 후 그룹의 스프라이트를 삭제하려면 xTrue으로 대체하십시오. 그렇게하고 싶지 않으면 xFalse으로 대체하십시오. 이것들은 충돌 탐지 코드의 기초이며, 이것이 당신을 도울 것을 희망합니다!