目標:知道什麼時候一個精靈點擊/主動用鼠標如何檢測鼠標和精靈之間的碰撞/鼠標懸停?
使用:Python的3.2 64位,pygame的1.92 64位,64位Windows 7
我花了6個小時無果......我嘗試:
s.rect.collidepoint(pygame.mouse.get_pos())
s.collidepoint(pygame.mouse.get_pos())
s.sprite.spritecollide(pygame.mouse.get_pos())
s.spritecollide(pygame.mouse.get_pos())
s.sprite.collide_rect(pygame.mouse.get_pos())
s.collide_rect(pygame.mouse.get_pos())
我也試着轉動鼠標的位置,我真的不想做,就像是有人在這裏提到的其他在另一個崗位,爲雪碧和碰撞一樣,具有相同的結果; (
我能夠succ essfully鼠標與圖像相撞,但只要我把圖像變成一個精靈類,它就成了一場噩夢......精靈類有什麼問題?或者我是在浪費時間試圖使用精靈來製作漂亮的碰撞特徵,而只是使用rect碰撞的圖像呢?
保持於獲取AttributeError的: '謝爾頓' 對象沒有屬性 '矩形'(s.Rect.collidepoint) 或AttributeError的: '元組' 對象沒有屬性 'collidepoint'(s.collidepoint) 或AttributeError的: 'Rake'對象沒有屬性'sprite'(s.sprite.collidepoint)
由於我是python/pygame的新手,我應該將這個檢測放在Sprite類本身的Update/Render方法中,或者我使用錯誤的事件輪詢?
我沒有打擾試圖重新編碼鼠標按下/上/拖動,因爲我甚至無法獲得鼠標懸停到
希望這一次的工作後得到一個工作響應......別人沒「T;(
感謝您的幫助
代碼:
import pygame
from pygame import *
from pygame.locals import *
from pygame.sprite import *
class Sheldon(Sprite):
def __init__(self):
Sprite.__init__(self)
self.image = transform.scale(image.load('sheldon.jpg').convert(),(230,310))
self.rect = self.image.get_rect()
class Rake(Sprite):
def __init__(self):
Sprite.__init__(self)
self.image = transform.scale(image.load('rake.jpg').convert(),(230,310))
self.rect = self.image.get_rect()
class Sprite_Mouse_Location(Sprite):
def __init__(self,x,y):
Sprite.__init__(self)
self.rect = pygame.Rect(x,y,1,1)
print(self.rect)
pygame.init()
window = display.set_mode((800,600))
sheldon = Sheldon()
sheldon.rect = (10,10)
all_sprites = Group(sheldon)
rake = Rake()
rake.rect = (400,250)
all_sprites.add(rake)
x,y = pygame.mouse.get_pos()
mouse_sprite = Sprite_Mouse_Location(x,y)
running = True
while running == True:
for event in pygame.event.get():
if event.type == QUIT or event.type == KEYUP and event.key == K_ESCAPE :
pygame.quit()
elif event.type == MOUSEMOTION :
for s in all_sprites :
if pygame.sprite.collide_rect(s,mouse_sprite):
print("hit")
window.fill((0,0,0))
all_sprites.update()
all_sprites.draw(window)
display.update()
你必須使用[pygame.Rect()](http://www.pygame.org/docs/ref/rect.html) – furas
我沒有,但它不工作要麼,但也許我有使用元組而不是(x,y,w,h)?我再次嘗試self.rect.collidepoint(x,y),但仍然無法讓它工作...反正它現在是固定的;) –