I'm developing the A.I. of my racing game, and I'm having an unforeseen problem. I manage to get the bot to drive by itself by accelerating in the direction of an angle that is returned using the atan2 trig function considering the position of previously-defined waypoints on the track data structure. Here's the code for ai.py
:
import math
import pygame
class Bot:
def __init__(self, player, track):
self.player = player
self.track = track
self.current_waypoint = 1
self.player.states[0] = True
self.track.choose_waypoint_path()
self.number_of_waypoints = len(self.track.waypoint_positions.keys())
self.get_waypoint_angle()
def get_waypoint_angle(self):
self.dx = self.track.waypoint_positions[self.current_waypoint][0] - self.player.car.pos[0]
self.dy = self.track.waypoint_positions[self.current_waypoint][1] - self.player.car.pos[1]
self.ratio = math.atan2(self.dy, self.dx)
self.angle = -self.ratio * (180/math.pi)
def think(self):
if pygame.Rect(self.player.car.pos, self.player.car.dimensions).collidepoint(
self.track.waypoint_positions[self.current_waypoint][0],
self.track.waypoint_positions[self.current_waypoint][1]
):
self.track.choose_waypoint_path()
self.number_of_waypoints = len(self.track.waypoint_positions.keys())
if self.current_waypoint == self.number_of_waypoints:
self.current_waypoint = 0
self.current_waypoint += 1
self.get_waypoint_angle()
self.player.car.angle = self.angle
self.player.car.rotate()
self.player.move()
The thing is, when I set the car angle based on the return of the atan2 function, self.player.car.angle = self.angle
, the car rotates/turns in an extremely unrealistic fashion. It works, but it means that I have to gradually steer the car, and then I face this problem. I don't know when to steer left or right, because the angle can be negative. If I do this, for example:
if self.player.car.angle > self.new_angle:
self.player.car.angle -= self.player.car.steering_speed
else:
self.player.car.angle += self.player.car.steering_speed
The bot drives to the next waypoint destination by weirdly driving in circles.
So, I know the direction in which the bot should drive, but based on its previous angle, I don't know whether it should steer left or right to reach that direction.