# Ian Binstock
# 6/12/2026
# Showing cursor tracking and the rotation transform

import pygame, sys, math

SCREEN_W = 800
SCREEN_H = 800
SPEED = 8
EASE = 0.75
TURN_SPEED = 4.5

RECT_W = 60
RECT_H = 34

def speedcap_circle(x1, y1, x2, y2, speed=8, ease=1.0):
    dx = x2 - x1
    dy = y2 - y1
    dist = math.sqrt(dx * dx + dy * dy)

    if dist > speed:
        # Accurate tracking using normalization and math
        x1 += (dx / dist) * speed * ease
        y1 += (dy / dist) * speed * ease
    else:
        # Snap to target
        x1 = x2
        y1 = y2

    return [x1, y1]


def main():

    # Basic set up
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
    pygame.display.set_caption("Cursor Tracking Car")
    clock = pygame.time.Clock()

    # Draw car
    base_surf = pygame.Surface((RECT_W, RECT_H), pygame.SRCALPHA)
    base_surf.fill("red")
    pygame.draw.rect(base_surf, "lightblue", (RECT_W - 16, RECT_H // 8, 12, RECT_H * 3 // 4))

    # Variables used for tracking
    # Start at (50,50)
    target = [float(SCREEN_W // 2), float(SCREEN_H // 2)]
    obj_x = float(SCREEN_W // 2)
    obj_y = float(SCREEN_H // 2)

    angle = 0.0

    # Game loop
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Target trails the mouse via speed cap
        mouse = pygame.mouse.get_pos()
        target = speedcap_circle(target[0], target[1], mouse[0], mouse[1], SPEED, EASE)

        # Object trails the target with smoothing
        obj_x += (target[0] - obj_x) * 0.35
        obj_y += (target[1] - obj_y) * 0.35

        dx = target[0] - obj_x
        dy = target[1] - obj_y
        # If moving, change angle as needed
        if abs(dx) > 0.5 or abs(dy) > 0.5:
            angle = math.degrees(math.atan2(-dy, dx)) # make sure to use -dy

        # Rotating alters the dimensions, recenter object
        rotated_surf = pygame.transform.rotate(base_surf, angle)
        rotated_rect = rotated_surf.get_rect(center=(int(obj_x), int(obj_y)))

        # Draw elements
        screen.fill("black")
        screen.blit(rotated_surf, rotated_rect)

        pygame.display.update()
        clock.tick(60)

# Run it
main()