Minggu, 12 April 2026

Python Animation - Drone 2

 





import tkinter as tk

import math


class QuadcopterAnimation:

    def __init__(self, root):

        self.root = root

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

        

        # Canvas setup

        self.canvas = tk.Canvas(root, width=600, height=400, bg="white")

        self.canvas.pack()

        

        # Initial position

        self.x, self.y = 300, 200

        self.angle = 0

        self.speed = 10

        self.running = False

        

        # Start button

        self.start_button = tk.Button(root, text="Start Animation", command=self.start_animation)

        self.start_button.pack()

        

        # Keyboard bindings

        self.root.bind("<w>", self.move_up)

        self.root.bind("<s>", self.move_down)

        self.root.bind("<a>", self.move_left)

        self.root.bind("<x>", self.move_right)


    def draw_quadcopter(self):

        self.canvas.delete("quadcopter")

        

        # Body

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

        

        # Propellers

        prop_positions = [(-40, -15), (40, -15), (-40, 15), (40, 15)]

        for dx, dy in prop_positions:

            self.draw_propeller(self.x + dx, self.y + dy)

            

    def draw_propeller(self, px, py):

        # Rotating propeller blades

        length = 15

        self.angle += 0.5

        x1 = px + length * math.cos(self.angle)

        y1 = py + length * math.sin(self.angle)

        x2 = px - length * math.cos(self.angle)

        y2 = py - length * math.sin(self.angle)

        self.canvas.create_line(x1, y1, x2, y2, width=3, fill="blue", tags="quadcopter")

        self.canvas.create_oval(px-3, py-3, px+3, py+3, fill="blue", tags="quadcopter")


    def animate(self):

        if self.running:

            self.draw_quadcopter()

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


    def start_animation(self):

        if not self.running:

            self.running = True

            self.animate()

            self.start_button.config(state="disabled")


    # Movement controls

    def move_up(self, event): self.y -= self.speed

    def move_down(self, event): self.y += self.speed

    def move_left(self, event): self.x -= self.speed

    def move_right(self, event): self.x += self.speed


if __name__ == "__main__":

    root = tk.Tk()

    app = QuadcopterAnimation(root)

    root.mainloop()

Tidak ada komentar: