2d police chase game problem

Hi, I’ve been working on my new godot project – a police chase game on an empty parking lot, for a while and I am hard stuck fixing my ai police code. They are like orbiting me and seem like they can’t steer properly toward the player-“car” this is my code and i hope someone can help me

extends CharacterBody2D

var speed = 400
var direction = Vector2.DOWN
var turn_speed = deg_to_rad(310)
var player: CharacterBody2D

func _ready():
randomize()
speed *= randf_range(0.8, 1.2)
player = get_node(“/root/parking/car”)

func _physics_process(delta: float) → void:

var predicted_player_position = player.global_position + player.velocity * 0.3

var to_predicted_position = (predicted_player_position - global_position).normalized()
var desired_angle = to_predicted_position.angle()
var angle_difference = wrapf(desired_angle - rotation, -PI, PI)


var max_turn = turn_speed * delta
angle_difference = clamp(angle_difference, -max_turn, max_turn)
rotation += angle_difference


velocity = speed * direction.rotated(rotation)
move_and_slide()

Did you try making your turn_speed value higher?

To format code you put on the forum:

To post GDScript code specifically, you should also put “gd” directly behind the starting ticks, for example
```gd
class_name Test
extends Node
```
will look like this:

class_name Test
extends Node
1 Like

Along the lines of @wchc 's suggestion, personally I’d try to get the code working without the max_turn clamp. When you’ve got the AI homing in properly, put the max_turn code back in. When a system isn’t working as expected, it can help to simplify it, and then gradually add complexity back in as you get each part working.

It may well be that max_turn is too low, which would certainly explain the donuts. It would, of course, be perfectly reasonable for your game to just explain away that the cops like donuts…

Assuming that’s not acceptable, consider how you’re calculating turn_speed. You’ve got that as deg_to_rad(310), and you’re multiplying by delta, so you’re effectively saying that the car has a turn speed of 310 degrees per second. One second’s worth of delta adds up to 1.0.

This means your car can’t do a full 360 degree turn within a second. It will take ~1.16 seconds to do a full 360 (calculated as 360 / max_turn…).

In your case, your speed is 400, so your car is moving 400/sec; in 1.16 seconds that’s 464 units (pixels, presumably). At maximum turn speed, the car completes a circle in 1.16 seconds, so we have a minimum turn circle with a circumference of 464. Divide that by 2π to get the radius, and we get ~74 pixels, or a diameter of 148 pixels.

Which sounds to me like a recipe for the cops doing donuts around you.

I think you’ll either want to raise max_turn or lower speed if you want them to be able to actually reach you.