如何使用鼠标水平移动对象,但在python中设置y位置

时间:2016-10-21 03:19:21

标签: python pygame

我试图复制街机游戏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()    

1 个答案:

答案 0 :(得分:1)

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

获得鼠标位置:

mousePos = pygame.mouse.get_pos()

你可能想要改变你划出宇宙飞船的方式。现在你已经指定了一个带有point1,point2和point3的三角形。它没有改变。我们这样做:

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()    
相关问题