Moving a Sprite in the direction of an angle in Pygame [duplicate]

*爱你&永不变心* 提交于 2021-02-05 07:25:06

问题


Im trying to move a sprite in the direction of an angle in pygame, using the left & right arrow keys to change the direction of the sprite but when I press the up key, the sprite just moves right. I have 2 variables that take speed and a velocity calculation and adds them together (vel_x & vel_y), I then add this to the position (orientation) of the sprite but it isnt following the sprite orientation when it moves forward (if keybd_tupl[K_UP]).

import pygame
import random
import math

from pygame.locals import *

window_wid = 800
window_hgt = 600

frame_rate = 50
delta_time = 1 / frame_rate
STATE_READY = 2

def game_loop_inputs():

    # look in the event queue for the quit event
    quit_ocrd = False
    for evnt in pygame.event.get():
        if evnt.type == QUIT:
            quit_ocrd = True

    return quit_ocrd

def game_loop_update(circle_hitbox):

    # start by assuming that no collisions have occurred
    circle_hitbox["col"] = False

    # return the new state of the rotating line and the circle hitbox
    return circle_hitbox


def game_loop_render(circle_hitbox, window_sfc):

    # clear the window surface (by filling it with black)
    window_sfc.fill( (0,0,0) )

    # draw the circle hitbox, in red if there has been a collision or in white otherwise
    if circle_hitbox["col"]:

        #pygame.draw.circle(window_sfc, (255, 0, 0), circle_hitbox["pos"], circle_hitbox["rad"])
        rotated_damage = pygame.transform.rotate(circle_hitbox["damage"], circle_hitbox["angle"])
        window_sfc.blit(rotated_damage, circle_hitbox["pos"])
    else:
        #pygame.draw.circle(window_sfc, (255, 255, 255), circle_hitbox["pos"], circle_hitbox["rad"])
        rotated_image = pygame.transform.rotate(circle_hitbox["sprite"], circle_hitbox["angle"])
        window_sfc.blit(rotated_image, circle_hitbox["pos"])

    # update the display
    pygame.display.update()


def main():

    # initialize pygame
    pygame.init()

    # create the window and set the caption of the window
    window_sfc = pygame.display.set_mode( (window_wid, window_hgt) )
    pygame.display.set_caption('"Toy" for the MDA Exercise')

    # create a clock
    clock = pygame.time.Clock()

    # this is the initial game state
    game_state = STATE_READY

#####################################################################################################
    # these are the initial game objects that are required (in some form) for the core mechanic provided
#####################################################################################################

    # this game object is a circulr
    circle_hitbox = {}
    circle_hitbox["pos"] = (window_wid // 2, window_hgt // 2)
    circle_hitbox["rad"] = 30
    circle_hitbox["col"] = False
    circle_hitbox["sprite"] = pygame.image.load("cars_racer_{}.png".format(random.randint(1, 3)))
    circle_hitbox["damage"] = pygame.image.load("cars_racer_red.png")
    circle_hitbox["crash"] = pygame.image.load("explosion.png")
    circle_hitbox["damaged"] = False
    circle_hitbox["angle"] = 0

    speed = 10.0
    vel_x = speed * math.cos(circle_hitbox["angle"] * (math.pi / 180))
    vel_y = speed * math.sin(circle_hitbox["angle"] * (math.pi / 180))

    # the game loop is a postcondition loop controlled using a Boolean flag
    closed_flag = False
    while not closed_flag:

    #####################################################################################################
        # this is the "inputs" phase of the game loop, where player input is retrieved and stored
    #####################################################################################################

        closed_flag = game_loop_inputs()

        keybd_tupl = pygame.key.get_pressed()
        if keybd_tupl[K_UP]:
            circle_hitbox["pos"] = (circle_hitbox["pos"][0] + vel_x, circle_hitbox["pos"][1] + vel_y)
            print(vel_y)
        if keybd_tupl[K_LEFT]:
            circle_hitbox["angle"] = (circle_hitbox["angle"] + 10.0)
        if keybd_tupl[K_RIGHT]:
            circle_hitbox["angle"] = (circle_hitbox["angle"] - 10.0)

    #####################################################################################################
        # this is the "update" phase of the game loop, where the changes to the game world are handled
    #####################################################################################################

        circle_hitbox = game_loop_update(circle_hitbox)

    #####################################################################################################
        # this is the "render" phase of the game loop, where a representation of the game world is displayed
    #####################################################################################################

        game_loop_render(circle_hitbox, window_sfc)

        # enforce the minimum frame rate
        clock.tick(frame_rate)

if __name__ == "__main__":
    main()

It just isnt working & I dont know why.


回答1:


You have to calculate the vel_x and vel_y in the while loop.

while not closed_flag:
    closed_flag = game_loop_inputs()

    keybd_tupl = pygame.key.get_pressed()
    if keybd_tupl[K_UP]:
        circle_hitbox["pos"] = (circle_hitbox["pos"][0] + vel_x, circle_hitbox["pos"][1] + vel_y)
        print(vel_y)
    if keybd_tupl[K_LEFT]:
        circle_hitbox["angle"] -= 1.0
    if keybd_tupl[K_RIGHT]:
        circle_hitbox["angle"] += 1.0

    # `math.radians` can be used instead of `* (math.pi / 180)`
    vel_x = speed * math.cos(math.radians(circle_hitbox["angle"]))
    vel_y = speed * math.sin(math.radians(circle_hitbox["angle"]))

Also, pass the negative angle to pygame.transform.rotate in the game_loop_render function:

rotated_damage = pygame.transform.rotate(circle_hitbox["damage"], -circle_hitbox["angle"])

The rotation probably still doesn't look right (I'm using some replacement images and they don't rotate correctly). Take a look at this answer if you want to know how to rotate pygame sprites and images around their center in pygame.



来源:https://stackoverflow.com/questions/48832717/moving-a-sprite-in-the-direction-of-an-angle-in-pygame

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