salzig1
salzig1

Reputation: 27

How can i make my randomly moving object move in a specific angle in pygame

Full Code

self.VEL = 3
self.RAND = numpy.linspace(-self.VEL, +self.VEL, 100)  # calculating value between -2 and 2, a total of 100 values
-----------------------------------------
if self.new_line:
    self.deltax = random.choice(self.RAND)
    self.deltay = random.choice(self.RAND)
    self.new_line = False
self.move(self.deltax, self.deltay)
-----------------------------------------
def move(self, deltax, deltay):
    self.x += deltax
    self.y += deltay

I'm currently building an ant simulator in python with pygame. The ants start in the middle and move on from there randomly. The movement works like this. Every few milliseconds self.new_line is set to True. Then a new self.deltax and self.deltay are calculated. Now, as long as self.new_line is False my ant will move with self.x += deltax and self.y += deltay per iteration. When self.new_line is True again the ant will start a new line with new values for self.deltax and self.deltay. The values for deltax and deltay are between -2 and +2 meaning the ant could move in every angle.

Visualization

Questions:

  1. However i want my ants only to move in a specific angle. Like This

How can i do this?

  1. If you run the program with on ant you will see that the speed of the ant changes with new lines. How can make my ant to have one consistent speed?

  2. How can i make my ant bounce of walls in a specific angle?

Thanks for your help.

Upvotes: 1

Views: 262

Answers (1)

Rabbid76
Rabbid76

Reputation: 210899

These are multiple questions. The intent is to ask only one question. I will only answer 2 of them.
Use pygame.math.Vector2 and rotate() to generate a direction vector with constant length and angle in a specified range:

if self.new_line:
    angle = random.randint(-45, 45)
    direction_vector = pygame.math.Vector2(0, -self.VEL).rotate(angle)
    self.deltax = direction_vector.x
    self.deltay = direction_vector.y

Upvotes: 1

Related Questions