2

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]
skrx
  • 19,980
  • 5
  • 34
  • 48
jotjern
  • 460
  • 5
  • 18

3 Answers3

2

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
Nick De Beer
  • 5,232
  • 6
  • 35
  • 50
ospahiu
  • 3,465
  • 2
  • 13
  • 24
  • Thanks this helped alot. I was wondering if you knew how to convert X and y to degrees, like point from one cordinate to another? Thanks, that would be helpfull! – jotjern Dec 30 '16 at 07:34
  • Glad it helped! I don't follow? You want to convert the cartesian coordinates `x` and `y` to degrees? Do you want to convert to polar coordinates? Or do you want to convert to some sort of longitude/latitude? – ospahiu Dec 30 '16 at 07:37
1

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

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()
skrx
  • 19,980
  • 5
  • 34
  • 48