Minggu, 12 April 2026

Python Animation - Drone 3

 




import tkinter as tk

import math


class QuadcopterAnimation:

    def __init__(self, root):

        self.root = root

        self.root.title("2D Quadcopter Simulation")

        

        # Canvas setup

        self.canvas = tk.Canvas(root, width=800, height=600, bg='white')

        self.canvas.pack()

        

        # Start button

        self.btn_start = tk.Button(root, text="Start Flight", command=self.start_animation)

        self.btn_start.pack()

        

        # Animation state

        self.running = False

        self.angle = 0

        self.propeller_angle = 0

        

    def draw_quadcopter(self, x, y):

        self.canvas.delete("quad") # Clear previous frame

        

        # Body

        body = self.canvas.create_rectangle(x-40, y-10, x+40, y+10, fill="black", tags="quad")

        

        # Propellers (rotating discs)

        prop_radius = 20

        prop_positions = [

            (x-40, y-20), (x+40, y-20), # Front

            (x-40, y+20), (x+40, y+20)  # Back

        ]

        

        for px, py in prop_positions:

            # Propeller disc

            self.canvas.create_oval(px-prop_radius, py-prop_radius, 

                                    px+prop_radius, py+prop_radius, 

                                    fill="#b3b3b3", outline="gray", tags="quad")

            # Rotating propeller blades

            self.draw_propeller_blades(px, py, prop_radius, self.propeller_angle, "quad")


    def draw_propeller_blades(self, px, py, radius, angle, tag):

        # Create a "spinning" blade effect

        for i in range(2):

            a = angle + (i * math.pi / 2) # Two blades per propeller

            self.canvas.create_line(

                px - math.cos(a) * radius, py - math.sin(a) * radius,

                px + math.cos(a) * radius, py + math.sin(a) * radius,

                width=3, fill="blue", tags=tag

            )


    def start_animation(self):

        if not self.running:

            self.running = True

            self.animate()

            

    def animate(self):

        if self.running:

            # --- Path Calculation (Smooth Elliptical Path) ---

            center_x, center_y = 400, 300

            radius_x, radius_y = 250, 150

            

            x = center_x + radius_x * math.cos(self.angle)

            y = center_y + radius_y * math.sin(self.angle)

            

            self.draw_quadcopter(x, y)

            

            # Update angles for movement and rotation

            self.angle += 0.02 # Flight speed

            self.propeller_angle += 0.5 # Propeller speed

            

            # Continue loop

            self.root.after(20, self.animate)


if __name__ == "__main__":

    root = tk.Tk()

    app = QuadcopterAnimation(root)

    root.mainloop()

Tidak ada komentar: