-->

Pygame point image towards mouse

2020-08-01 06:45发布

问题:

I am trying to get this image 'spaceship' to point towards my mouse on screen, proving to be quite difficult so I would appreciate any help :O Also, would appreciate it if you could help with moving an image towards the cursor, i'm guessing that would be quite similar to rotating towards it.. Heres my code:

import sys, pygame, math;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
backg = ('background.jpg')
pygame.init()
screen = pygame.display.set_mode((800, 600))
bk = pygame.image.load(backg).convert_alpha()
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN and event.button == 1:
            print("test1")
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            print("test3")
    screen.blit(bk, (0, 0))
    pos = pygame.mouse.get_pos()
    screen.blit(mousec, (pos))
    screen.blit(space_ship, (400, 300)) #I need space_ship to rotate towards my cursor
    pygame.display.update()

回答1:

Here:

import sys, pygame, math;
from pygame.locals import *;
spaceship = ('spaceship.png')
mouse_c = ('crosshair.png')
backg = ('background.jpg')
pygame.init()
screen = pygame.display.set_mode((800, 600))
bk = pygame.image.load(backg).convert_alpha()
mousec = pygame.image.load(mouse_c).convert_alpha()
space_ship = pygame.image.load(spaceship).convert_alpha()
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEBUTTONDOWN and event.button == 1:
            print("test1")
        elif event.type == MOUSEBUTTONDOWN and event.button == 3:
            print("test3")
    screen.blit(bk, (0, 0))
    pos = pygame.mouse.get_pos()
    screen.blit(mousec, (pos))
    angle = 360-math.atan2(pos[1]-300,pos[0]-400)*180/math.pi
    rotimage = pygame.transform.rotate(space_ship,angle)
    rect = rotimage.get_rect(center=(400,300))
    screen.blit(rotimage,rect) #I need space_ship to rotate towards my cursor
    pygame.display.update()

First get the angle between the space ship and the mouse, then rotate the image and set the center of the image so the image doesn't move around while rotating.



标签: python pygame