gpt4 book ai didi

python - 我怎样才能让一个对象随着鼠标水平移动,但在Python中有一个设置的y位置

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:44 24 4
gpt4 key购买 nike

我正在尝试复制街机游戏 galaga 中的宇宙飞船。宇宙飞船需要比鼠标移动得慢,但仍会跟随它。这就是我到目前为止所拥有的,我不知道从这里该去哪里。请帮忙请记住,我是编程新手,所以我确信这很难看。

import pygame
import math
pygame.display.init()
pygame.mixer.init()
screen = pygame.display.set_mode((800, 600))

#fireSnd = pygame.mixer.Sound()
#pygame.mixer.music.load()
#pygame.mixer.music.play(-1)
x1 = 400
x2 = 405
x3 = 395
point1 = (x1,585)
point2 =(x2,600)
point3 = (x3,600)
SpaceShip = (point1,point2,point3)
Hdir = 0

done = False

while not done:
# Step1. Erase the screen
screen.fill((0, 0, 0))
# Step2. Update

# Step3. Process variables
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
elif event.type == pygame.MOUSEMOTION:
x,y = event.pos
# Step4. Drawing
pygame.draw.polygon(screen, (255,0,0) ,(SpaceShip), 0)
pygame.display.flip()



pygame.display.quit()

最佳答案

如果鼠标位于船的左侧,则让您的船以 x 速率向左移动;如果鼠标位于船的右侧,则以 x 速率向右移动。

获取鼠标位置:

mousePos = pygame.mouse.get_pos()

您可能想改变绘制宇宙飞船的方式。现在您已经指定了一个包含点 1、点 2 和点 3 的三角形。它没有改变。让我们做这样的事情:

spaceshipPos = [400]

Spaceship = ((spaceshipPos[0],585),(spaceshipPos[0] + 5,600),(spaceshipPos[0] - 5,600))

这只是获取宇宙飞船的位置并给出每个三角形点的位置。

while True: # game loop

if spaceshipPos[0] > mousePos[0]: # if the mouse is to the left, move left
spaceshipPos[0] -= 5
elif spaceshipPos[0] < mousePos[1]: # if the mouse is to the right, move right
spaceshipPos[0] += 5

pygame.draw.polygon(screen, (255,0,0), Spaceship, 0)

所以你的完整代码是:

import pygame
import math
pygame.display.init()
pygame.mixer.init()
screen = pygame.display.set_mode((800, 600))

#fireSnd = pygame.mixer.Sound()
#pygame.mixer.music.load()
#pygame.mixer.music.play(-1)

Hdir = 0

moveRate = 1

spaceshipPos = [400]

done = False

while not done:

screen.fill((0, 0, 0))

event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True

mousePos = pygame.mouse.get_pos()

if spaceshipPos[0] > mousePos[0]: # if the mouse is to the left, move left
spaceshipPos[0] -= moveRate

elif spaceshipPos[0] < mousePos[0]: # if the mouse is to the right, move right
spaceshipPos[0] += moveRate

elif spaceshipPos[0] == mousePos[0]:
pass

Spaceship = ((spaceshipPos[0],585),(spaceshipPos[0] + 5,600),(spaceshipPos[0] - 5,600))
pygame.draw.polygon(screen, (255,0,0) ,(Spaceship), 0)

pygame.display.flip()



pygame.display.quit()

关于python - 我怎样才能让一个对象随着鼠标水平移动,但在Python中有一个设置的y位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com