鼠標移動方塊的mask碰撞檢測原理示例程序

"""
   鼠標移動方塊的mask碰撞檢測原理示例程序
"""
import pygame
from pygame.locals import * 

pygame.init()
screen = pygame.display.set_mode((480,360))
pygame.display.set_caption("鼠標移動方塊的mask碰撞檢測原理示例程序by 李興球")

# 靜止不動的紅色方塊
width,height = 50,50
x1,y1 = 100,100
redsquare = pygame.Surface((width,height)).convert_alpha()
redsquare.fill((255,10,10,228))                # 最後的0代表完全透明
redsquare_rect = redsquare.get_rect(topleft=(x1,y1))  # 定位
redmask = pygame.mask.from_surface(redsquare)  # 取掩膜

# 用鼠標移動的藍色方塊
x2,y2 = pygame.mouse.get_pos()
bluesquare = pygame.Surface((width,height)).convert_alpha()
bluesquare.fill((10,10,255))
bluesquare_rect = bluesquare.get_rect(topleft=(x2,y2)) # 定位
bluemask = pygame.mask.from_surface(bluesquare) # 取掩膜

running=True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:running=False

    x2,y2  = pygame.mouse.get_pos()
    bluesquare_rect.topleft = (x2,y2 )
    offset = x1 -x2 , y1 - y2
    # 返回的p是相對於bluemask的偏移量
    p = bluemask.overlap(redmask,offset)
    if p:
        碰撞點 = bluesquare_rect.x + p[0],bluesquare_rect.y + p[1]
        info = "offset=" + str(offset) + ",p=" + str(p) + ",碰撞點座標:" + str(碰撞點)
        pygame.display.set_caption(info)
    else:
        pygame.display.set_caption("無碰撞")
    screen.fill((0,0,0))
    screen.blit(redsquare,redsquare_rect)
    screen.blit(bluesquare,bluesquare_rect)     # 貼到屏幕

    pygame.display.update()

pygame.quit()

# 提示:本博客幾乎不更新,需要Python創意遊戲動畫代碼請百度一下:李興球
# 找到博客  lixingqiu.com 

pygame鼠標移動方塊的mask碰撞檢測原理示例程序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章