import tkinter as tk
import math
import time
class DroneAnimation:
def __init__(self, root):
self.root = root
self.root.title("2D Drone Animation with Rotating Propellers")
# Canvas setup
self.canvas_width = 800
self.canvas_height = 400
self.canvas = tk.Canvas(root, width=self.canvas_width, height=self.canvas_height, bg="skyblue")
self.canvas.pack()
# Drone properties
self.drone_width = 120
self.drone_height = 40
self.propeller_radius = 15
self.spokes = 4
self.angle = 0 # rotation angle for propellers
self.speed = 3 # horizontal speed
# Initial drone position
self.x = 50
self.y = 200
# Draw drone body and propellers
self.body = self.canvas.create_rectangle(
self.x, self.y,
self.x + self.drone_width, self.y + self.drone_height,
fill="gray", outline="black"
)
# Propeller positions (relative to body)
self.propeller_offsets = [
(-20, -20), # top-left
(self.drone_width + 20, -20), # top-right
(-20, self.drone_height + 20), # bottom-left
(self.drone_width + 20, self.drone_height + 20) # bottom-right
]
# Create propeller spoke lines
self.propellers = []
for _ in range(4):
lines = []
for _ in range(self.spokes):
line = self.canvas.create_line(0, 0, 0, 0, fill="black", width=2)
lines.append(line)
self.propellers.append(lines)
self.animate()
def draw_propeller(self, cx, cy, angle, lines):
"""Draws a propeller with spokes rotated by given angle."""
spoke_angle = 360 / self.spokes
for i, line in enumerate(lines):
theta = math.radians(angle + i * spoke_angle)
x_end = cx + self.propeller_radius * math.cos(theta)
y_end = cy + self.propeller_radius * math.sin(theta)
self.canvas.coords(line, cx, cy, x_end, y_end)
def animate(self):
# Move drone horizontally
self.x += self.speed
if self.x > self.canvas_width:
self.x = -self.drone_width # wrap around
# Update drone body position
self.canvas.coords(
self.body,
self.x, self.y,
self.x + self.drone_width, self.y + self.drone_height
)
# Update propellers
self.angle = (self.angle + 20) % 360 # rotation speed
for idx, (dx, dy) in enumerate(self.propeller_offsets):
cx = self.x + dx
cy = self.y + dy
self.draw_propeller(cx, cy, self.angle, self.propellers[idx])
# Schedule next frame
self.root.after(50, self.animate)
if __name__ == "__main__":
root = tk.Tk()
app = DroneAnimation(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar