Pygame point image towards mouse

点点圈 提交于 2020-06-11 12:51:48

问题


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.



来源:https://stackoverflow.com/questions/20162302/pygame-point-image-towards-mouse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!