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=800, height=600, bg='white')
self.canvas.pack()
# Start Button
self.start_button = tk.Button(root, text="Start Quadcopter", command=self.start_animation)
self.start_button.pack()
# State variables
self.x, self.y = 400, 300
self.scale = 1.0
self.angle = 0
self.running = False
self.speed = 10
# Keyboard bindings
self.root.bind("<KeyPress-w>", lambda e: self.move(0, -self.speed))
self.root.bind("<KeyPress-s>", lambda e: self.move(0, self.speed))
self.root.bind("<KeyPress-a>", lambda e: self.move(-self.speed, 0))
self.root.bind("<KeyPress-d>", lambda e: self.move(self.speed, 0))
self.root.bind("<KeyPress-1>", lambda e: self.zoom(1.1)) # Zoom In
self.root.bind("<KeyPress-2>", lambda e: self.zoom(0.9)) # Zoom Out
def start_animation(self):
if not self.running:
self.running = True
self.start_button.config(state=tk.DISABLED)
self.animate()
def move(self, dx, dy):
self.x += dx
self.y += dy
def zoom(self, factor):
self.scale *= factor
def draw_quad(self):
self.canvas.delete("quad")
s = self.scale
# Main body
body_coords = [self.x - 40*s, self.y - 10*s, self.x + 40*s, self.y + 10*s]
self.canvas.create_rectangle(body_coords, fill="grey", tags="quad")
# Propellers (4 corners)
props = [
(self.x - 35*s, self.y - 15*s),
(self.x + 35*s, self.y - 15*s),
(self.x - 35*s, self.y + 15*s),
(self.x + 35*s, self.y + 15*s)
]
for px, py in props:
# Rotating Propeller Blades
r = 15 * s
self.canvas.create_oval(px-r, py-r, px+r, py+r, outline="black", tags="quad")
# Drawing propeller blades based on rotation angle
for i in range(2):
angle = self.angle + i * math.pi / 2
self.canvas.create_line(
px, py,
px + r * math.cos(angle), py + r * math.sin(angle),
fill="blue", width=2, tags="quad"
)
def animate(self):
if self.running:
self.angle += 0.5 # Propeller speed
self.draw_quad()
self.root.after(50, self.animate) # 20 frames per second [4]
if __name__ == "__main__":
root = tk.Tk()
app = QuadcopterAnimation(root)
root.mainloop()

Tidak ada komentar:
Posting Komentar