Move in degrees pygame

1.7k views Asked by At

I am making a utility for myself to easily translate degrees to x and y cordinates in my games and I got stuck on a problem; trying to move the player in degrees across the screen. I found multiple formulas that didn't work and I need some help. Here is my code that I found:

def move(degrees, offset):
    x = math.cos(degrees * 57.2957795) * offset  # 57.2957795 Was supposed to be the
    y = math.sin(degrees * 57.2957795) * offset  # magic number but it won't work.
    return [x, y]

I then ran this:

move(0, 300)

Output:

[300.0, 0.0]

and it worked just fine, but when I did this:

move(90, 300)

it outputted this:

[-89.8549554331319, -286.22733444608303]
3

There are 3 answers

2
ospahiu On BEST ANSWER

Your approach is almost correct. You should use radians for sin/cos functions. Here is a method I commonly use in C++ (ported to python) for 2D movement.

import math
def move(degrees, offset)
    rads = math.radians(degrees)
    x = math.cos(rads) * offset
    y = math.sin(rads) * offset
    return x, y
3
Ignacio Vazquez-Abrams On

The number is correct, but the operation is wrong. In order to convert degrees to radians you need to divide by 180 degrees per half-circle and then multiply by pi radians per half-circle. This is equivalent to dividing by the constant you have.

0
skrx On

You can use the from_polar method of the pygame.math.Vector2 class to set the polar coordinates of a vector. Then you can use this vector to adjust the position of a sprite or rect.

import pygame as pg
from pygame.math import Vector2


def move(offset, degrees):
    vec = Vector2()  # Create a zero vector.
    vec.from_polar((offset, degrees))  # Set its polar coordinates.
    return vec


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')

rect = pg.Rect(300, 200, 30, 20)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                # Use the vector that `move` returns to move the rect.
                rect.move_ip(move(50, 90))

    screen.fill(BG_COLOR)
    pg.draw.rect(screen, BLUE, rect)
    pg.display.flip()
    clock.tick(30)

pg.quit()