我正在创建一个游戏,其中玩家位于表面的中央。这个表面而不是这个玩家四处移动我希望能够添加诸如剑之类的对象。我有一个问题,当我第一次开始游戏时,我可以将鼠标光标放在对象上,但是当我四处移动时,将鼠标光标放在对象上不会做任何事情,而在另一个区域,它会做它应该做的事情。我认为随着 map 的移动,它会离开屏幕,从而改变鼠标落在对象上的位置。我创建此示例是为了说明我的意思
import pygame
width,height = 800,600
screen = pygame.display.set_mode((width,height))
world = pygame.Surface((20 * 32, 40 * 32))
itemPos = (4,8)
for x in range(20):
for y in range(40):
pygame.draw.rect(world, (255,0,0), (x * 32,y * 32,32,32), 2)
x,y = 0,0
while True:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
key = pygame.key.get_pressed()
if key[pygame.K_w]:
y += 10
if key[pygame.K_s]:
y -= 10
if key[pygame.K_a]:
x += 10
if key[pygame.K_d]:
x -= 10
screen.blit(world, (x,y))
mouse = pygame.mouse.get_pos()
pygame.draw.rect(world, (0,255,0), (itemPos[0] * 32,itemPos[1] * 32,20,20))
if mouse[0] > itemPos[0] * 32 and mouse[0] < (itemPos[0] * 32) + 32:
if mouse[1] > itemPos[1] * 32 and mouse[1] < (itemPos[1] * 32) + 32:
print("Mouse is over item")
pygame.display.update()
红色空心方 block 就是 map 。然后较小的绿色方 block 是我测试光标是否结束的对象。尝试代码并四处移动一下,然后尝试将光标放在绿色对象上以获取 mouse is over item。这基本上就是我想要实现但无法弄清楚的目标
请您参考如下方法:
你需要意识到,当你创建一个带有滚动/相机/移动 map 的游戏时,你正在处理两种不同的坐标:
世界坐标(逻辑坐标,例如
(0, 0)总是(0, 0),没有不管滚动/相机或 map 移动屏幕坐标(用于确定某物在实际屏幕上的实际位置,例如
itemPos = (4,8)在世界坐标中,并转换为屏幕坐标乘以 32:(itemPos[0] * 32,itemPos[1] * 32)。
因此,当您读取鼠标位置时,您将获得屏幕坐标。然后,您必须将它们转换为世界坐标,或者根据您的 item 的屏幕坐标进行检查。
你已经到这里了:
if mouse[0] > itemPos_rel[0] * 32 and mouse[0] < (itemPos_rel[0] * 32) + 32:
但您没有查看 map 的滚动/移动。
所以要么平移鼠标位置:
...
mouse = pygame.mouse.get_pos()
mouse = mouse[0] - x, mouse[1] - y
...
或更好(请注意,我不再更改背景表面):
...
clock = pygame.time.Clock()
i=0
def world2screen(pos, scrolling):
return pos[0] * 32 + scrolling[0], pos[1] * 32 + scrolling[1]
while True:
...
screen.blit(world, (x,y))
item_pos_screen = world2screen(itemPos, (x, y))
pygame.draw.rect(screen, (0,255,0), (*item_pos_screen,20,20))
mouse = pygame.mouse.get_pos()
if mouse[0] > item_pos_screen[0] and mouse[0] < item_pos_screen[0] + 32:
if mouse[1] > item_pos_screen[1] and mouse[1] < item_pos_screen[1] + 32:
i+=1
print("Mouse is over item" + str(i))
pygame.display.update()
clock.tick(60)
或者更好的事件:
...
clock = pygame.time.Clock()
i=0
def world2screen(pos, scrolling):
return pos[0] * 32 + scrolling[0], pos[1] * 32 + scrolling[1]
def screen2world(pos, scrolling):
return int((pos[0] - scrolling[0]) / 32), int((pos[1] - scrolling[1]) / 32 )
while True:
...
screen.blit(world, (x,y))
item_pos_screen = world2screen(itemPos, (x, y))
pygame.draw.rect(screen, (0,255,0), (*item_pos_screen,20,20))
mouse = pygame.mouse.get_pos()
mouse_pos_world = screen2world(mouse, (x, y))
if mouse_pos_world == itemPos:
i+=1
print("Mouse is over item" + str(i))
pygame.display.update()
clock.tick(60)
