像素完美碰撞,命中掩码/空白错误
我正在试图理解完美像素碰撞的工作原理,我已经用pyGame窗口中弹来跳去的两个圆圈(图像)做了一个程序。脚本是这样的:
选择 | 换行 | 行号
- import pygame, importedfunctions, random
- pygame.init()
- clock = pygame.time.Clock()
- screen = pygame.display.set_mode([640,480])
- class BallClass(pygame.sprite.Sprite):
- def __init__(self, x,y):
- pygame.sprite.Sprite.__init__(self)
- self.image = pygame.image.load("ball.png")
- self.rect = self.image.get_rect()
- self.rect.left = x
- self.rect.top = y
- self.speed = [6,6]
- def move(self):
- global ballgroup
- x = self.rect.left
- self.rect.left += self.speed[0]
- y = self.rect.top
- self.rect.top += self.speed[1]
- if self.rect.left < 0 or self.rect.right > screen.get_width():
- self.speed[0] *= -1
- self.rect.left = x
- if self.rect.top < 0 or self.rect.bottom > screen.get_height():
- self.rect.top = y
- self.speed[1] *= -1
- for i in ballgroup:
- z = importedfunctions.PixelPerfectCollision(self, i)
- if z == True:
- self.speed[0] *= -1
- self.speed[1] *= -1
- print "collide!"
- else: print z
- ballgroup = pygame.sprite.Group()
- ball1 = BallClass(20,20)
- ballgroup.add(ball1)
- ball2 = BallClass(200,20)
- ballgroup.add(ball2)
- def blitting():
- global ballgroup, screen
- screen.fill([0,0,0])
- for i in ballgroup:
- i.move()
- for i in ballgroup:
- screen.blit(i.image,i.rect)
- stop = False
- def while_loop():
- while stop == False:
- clock.tick(30)
- blitting()
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- sys.exit()
- pygame.display.flip()
- while_loop()
它使用了PYGAME和以下脚本:
选择 | 换行 | 行号
- def PixelPerfectCollision(obj1, obj2):
- """
- If the function finds a collision, it will return True;
- if not, it will return False. If one of the objects is
- not the intended type, the function instead returns None.
- """
- try:
- #create attributes
- rect1, mask1, blank1 = obj1.rect, obj1.hitmask, obj1.blank
- rect2, mask2, blank2 = obj2.rect, obj2.hitmask, obj2.blank
- #initial examination
- if rect1.colliderect(rect2) is False:
- return False
- except AttributeError:
- return None
- #get the overlapping area
- clip = rect1.clip(rect2)
- #find where clip's top-left point is in both rectangles
- x1 = clip.left - rect1.left
- y1 = clip.top - rect1.top
- x2 = clip.left - rect2.left
- y2 = clip.top - rect2.top
- #cycle through clip's area of the hitmasks
- for x in range(clip.width):
- for y in range(clip.height):
- #returns True if neither pixel is blank
- if mask1[x1+x][y1+y] is not blank1 and \
- mask2[x2+x][y2+y] is not blank2:
- return True
- #if there was neither collision nor error
- return False
问题是它总是返回"None"(这使得球在每个球之间运行),我唯一确定的是它应该是带有obj.hit掩码和obj.Blank的对象
希望你能理解这个问题:/
我将非常感谢能帮上忙的人
请帮帮忙