【发布时间】:2015-05-19 05:48:49
【问题描述】:
您好,我一直在创建一个游戏,玩家必须躲避油桶,并且一直在努力获得 rect,这样我就可以在 2 个 sprite 碰撞时创建一些东西。但是,碰撞框似乎搞砸了,因为每当我启动游戏时,它都会自动检测到玩家和枪管之间的碰撞。
这是我的代码:
import pygame
import os
import time
import sys
import pyganim
import random
global rand
from threading import Thread
class UpdateThread(Thread):
def __init__(self):
self.stopped = False
Thread.__init__(self)
def run(self):
while not self.stopped:
self.downloadValue()
time.sleep(2)
def downloadValue(self):
rand=random.randrange(1, 10)
class oil(object):
def __init__(self):
self.image = pygame.image.load('oil.png')
self.image = pygame.transform.scale(self.image,(300,300))
self.rect = self.image.get_rect()
self.x = 1600
self.y = 400
def handle_keys(self):
key = pygame.key.get_pressed()
distance = 10
self.x -= distance
def draw(self, surface):
surface.blit(self.image, (self.x, self.y))
def checkCollision(self, oil, sprite):
col = sprite.colliderect(oil)
if col == True:
print ("GameOver")
def blit_alpha(target, source, location, opacity):
x = location[0]
y = location[1]
temp = pygame.Surface((source.get_width(), source.get_height())).convert()
temp.blit(target, (-x, -y))
temp.blit(source, (0, 0))
temp.set_alpha()
target.blit(temp, location)
class sprite(object):
def __init__(self):
self.image = pygame.image.load('image1.png')
self.rect = self.image.get_rect()
self.x = 0
self.y = 0
def handle_keys(self):
key = pygame.key.get_pressed()
distance = 10
if key[pygame.K_DOWN]:
self.y += distance
if key[pygame.K_UP]:
self.y -= distance
if key[pygame.K_RIGHT]:
self.x += distance
if key[pygame.K_LEFT]:
self.x -= distance
def draw(self, surface):
#surface.blit(self.image, (self.x, self.y))
anim.blit(surface, (self.x, self.y))
anim = pyganim.PygAnimation([("image1.png", 0.5), ("image2.png", 0.5)])
pygame.init()
screen = pygame.display.set_mode((1600, 800))
oil=oil()
sprite=sprite()
clock = pygame.time.Clock()
backgroundo= pygame.image.load('background.png')
background = pygame.transform.scale(backgroundo, (1600, 800))
anim.play()
myThread = UpdateThread()
myThread.start()
oil.checkCollision(oil.rect,sprite.rect)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
sprite.handle_keys()
oil.handle_keys()
screen.fill((255,255,255))
blit_alpha(screen, background, (0, 0), 128)
sprite.draw(screen)
oil.draw(screen)
pygame.display.update()
clock.tick(30)
任何帮助将不胜感激。
【问题讨论】:
-
checkCollision中的第一行应该是:col = sprite.colliderect(oil)-- 之后,你就自己动手了。
标签: python python-3.x pygame rect