Question

I am making a snake game in python with pygame and for moving the character I have a integer which is the degrees of the angle it should move. Is there any way I can get the change in x and y to move it based on the degrees? For example: func(90) # [0, 5] or func(0) # [5, 0]

Was it helpful?

Solution

import math

speed = 5
angle = math.radians(90)    # Remember to convert to radians!
change = [speed * math.cos(angle), speed * math.sin(angle)]

OTHER TIPS

The sine and cosine of the angle, multiplied by the total amount of the move, will give you the X and Y changes.

import math
def func(degrees, magnitude):
    return magnitude * math.cos(math.radians(degrees)), magnitude * math.sin(math.radians(degrees))

>>> func(90,5)
(3.0616169978683831e-16, 5.0)
>>> func(0,5)
(5.0, 0.0)

If the snake can only move at certain angles (e.g. 90 or 45 degrees), which is typical in such a game, there are only 4 or 8 directions you can go. You can just divide your angle by the permitted increment and get a direction index, which can then be used to index into a table of X/Y offsets. This will be a lot faster than using trigonometry.

x, y = 100, 100   # starting position of the snake

direction = angle / 90 % 4   # convert angle to direction

directions = [(0,-1), (1, 0), (0, 1), (-1, 0)]   # up, right, down, left

# convert the direction to x and y offsets for the next move
xoffset, yoffset = directions[direction]

# calculate the next move
x, y = x + xoffset, y + yoffset

Better yet, dispense with the angle concept entirely and just use a direction variable. Then rotating the snake is a simple matter of incrementing or decrementing the direction.

# rotate counter-clockwise
direction = (direction - 1) % 4

# rotate clockwise
direction = (direction + 1) % 4

This can easily be extended to 8 directions (moving at 45 degree increments) if desired.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top