2016-12-05 4 views
0

だから私は物事をかわす必要がある小さなゲームを書いたが、その後私は衝突の機能を見て、ちょうど衝突するコードでハードコードされた結託を変更することを知った。私はそれを設定しましたが、それはwokred didntなので、私はそれをテストし、新しいpygameファイルを作成しました!私の衝突が働いていない

import pygame 
w=400;h=400 
pygame.init() 
root=pygame.display.set_mode((w,h)) 
pygame.display.set_caption('TEST SUBJECT') 
def gameloop(): 
    thing=pygame.image.load('unnamed.png') 
    th=thing.get_rect() 
    thing2=pygame.image.load('s.png') 
    th2=thing2.get_rect() 
    clock=pygame.time.Clock() 
    while 1: 
     for event in pygame.event.get(): 
      if event.type==pygame.QUIT: 
       pygame.quit() 
       quit() 
      root.blit(thing,(w//2-50,h//2-60)) 
      root.blit(thing2,(0,0)) 
     if th.colliderect(th2)==1: 
      print('OK') 
     pygame.display.update() 
     clock.tick(15) 
gameloop() 

あなたがここで言うことができるように、衝突は2つのオブジェクトが互いに当たっても1を返します。

+1

あなたは 'th'と' th2'を変更しないので、彼らはお互いにヒットします。それを別の場所に表示することは重要ではありません。 'root.blit(thing、th)'と 'root.blit(thing、th2)'を試して、衝突していることがわかります。 – furas

答えて

0

thと​​を変更していないため、それらは互いに衝突します。

別の場所に表示しても問題ありません。

root.blit(thing, th) 
root.blit(thing, th2) 

を試してみて、あなたは彼らが衝突していることがわかります。

あなたは位置を変更すると、その後th.colliderect(th2)が動作するth.yth.xth.yまたはth2.xを変更する必要があります。


EDIT:フル実施例

import pygame 

# --- constants --- (UPPER_CASE names) 

WIDTH = 400 
HEIGHT = 400 

BLACK = (0, 0, 0) 

FPS = 25 

# --- main --- (lower_case names) 

# - init - 

pygame.init() 

root = pygame.display.set_mode((WIDTH, HEIGHT)) 
root_rect = root.get_rect() 

# - objects - 

thing1 = pygame.image.load('ball-1.png') 
thing1_rect = thing.get_rect() 

thing2 = pygame.image.load('ball-2.png') 
thing2_rect = thing2.get_rect() 

# move things 
thing1_rect.left = root_rect.left 
thing1_rect.centery = root_rect.centery 

thing2_rect.right = root_rect.right 
thing2_rect.centery = root_rect.centery 

# - mainloop - 

clock = pygame.time.Clock() 

while True: 

    # - events - 

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

    # - updates (without draws) - 

    # move objects 
    thing1_rect.x += 5 
    thing2_rect.x -= 5 

    # check collisions 
    if thing1_rect.colliderect(thing2_rect): 
     print('Collision') 

    # - draws (without updates) - 

    root.fill(BLACK) 
    root.blit(thing1, thing1_rect) 
    root.blit(thing2, thing2_rect) 

    pygame.display.update() 

    # - FPS - 

    clock.tick(FPS) 

ボール-1.png

enter image description here

ボール-2.png

enter image description here

+0

'(w // 2-50、h // 2-60)'と '(0,0)'を使って画像を表示しますが、画面上では触れませんが、 'th'と' th2 '(0,0)'と '(0,0)'の衝突をチェックして衝突させます。表示、衝突のチェック、位置の変更には、thとth2のみを使用してください。 – furas

関連する問題