pygame.sprite.collide_rect
またはを使用すると衝突が検出されますがpygame.sprite.collide_circle
、ビットマスクをスプライトに割り当てて実行しようとすると、衝突が検出されません。(wall.collision_action()
は、最初の円を他の円と同じ速度と方向で移動させます)これは今のところ問題ではありません
が、pygame.sprite.collide_circle を正常に動作させる円の画像を使用しているため、将来的にはより詳細で非円形のスプライトを使用すると、それになります。
コード:
import pygame, sys, math
from pygame.locals import *
pygame.init()
class ball_class(pygame.sprite.Sprite):
def __init__(self, surface):
self.surface = surface
self.x = 250
self.y = 250
self.vy = 0
self.vx = 0
self.sprite = pygame.sprite.Sprite()
self.sprite.image = pygame.image.load("ball.png").convert()
self.sprite.rect = self.sprite.image.get_rect(center = (self.x, self.y))
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def event(self, event):
if event.key == K_UP:
self.vy = -1
self.vx = 0
elif event.key == K_DOWN:
self.vy = 1
self.vx = 0
elif event.key == K_LEFT:
self.vx = -1
self.vy = 0
elif event.key == K_RIGHT:
self.vx = 1
self.vy = 0
def move(self):
self.y += self.vy
self.x += self.vx
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def draw(self, surface):
surface.blit(self.sprite.image, self.sprite.rect)
def position(self):
return self.sprite.rect()
class wall_class(pygame.sprite.Sprite):
def __init__(self, surface):
self.surface = surface
self.x = 250
self.y = 100
self.vy = 0
self.sprite = pygame.sprite.Sprite()
self.sprite.image = pygame.image.load("ball.png").convert()
self.sprite.rect = self.sprite.image.get_rect(center = (self.x, self.y))
self.sprite.rect.topleft = [int(self.x), int(self.y)]
self.sprite.mask = pygame.mask.from_surface(self.sprite.image)
def draw(self, surface):
surface.blit(self.sprite.image, self.sprite.rect)
def collision_action(self):
self.vy = ball.vy
self.vx = ball.vx
self.x += self.vx
self.y += self.vy
self.sprite.rect.topleft = [int(self.x), int(self.y)]
def gameQuit():
pygame.quit()
sys.exit()
screen = pygame.display.set_mode((500, 500), 0, 32)
ball = ball_class(screen)
wall = wall_class(screen)
clock = pygame.time.Clock()
while True:
screen.fill((0, 0, 0))
ball.move()
ball.draw(screen)
wall.draw(screen)
is_a_collision = pygame.sprite.collide_mask(wall.sprite, ball.sprite)
if is_a_collision:
wall.collision_action()
for event in pygame.event.get():
if event.type == QUIT:
gameQuit()
elif event.type == KEYDOWN:
ball.event(event)
clock.tick(100)
pygame.display.update()