Write a simple program with whatever coding language about a white stickerman that's floating in the black screen, a timeline is in the button which is for animating the stickerman, the stickerman has bones that can be manipulated, the timeline adds a simple key frame if you manipulate the stickerman.
Assistant
Sure! Below is a simple Python program using the Pygame library that creates a white stickman floating on a black screen. The stickman has bones that can be manipulated by clicking and dragging the joints. There's a timeline at the bottom of the screen, and it adds a keyframe whenever you manipulate the stickman.
Prerequisites
Python 3.x installed on your system.
Pygame library installed. You can install it using the following command:
bash
pip install pygame
Program Overview
Stickman Representation: The stickman is composed of bones connected by joints. Each bone is a line segment that can rotate around its starting point.
Bone Manipulation: You can click and drag the joints (endpoints of bones) to manipulate the stickman's pose.
Timeline: At the bottom is a simple timeline that shows keyframes. When you manipulate the stickman, press the 'K' key to add a keyframe.
Animation Playback: Press the Spacebar to toggle playback of the animation. The stickman's movement will interpolate between keyframes.
The Code
python
import pygame
import sys
from pygame.math import Vector2
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
TIMELINE_HEIGHT = 100
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Stickman Animator")
# Clock for controlling the frame rate
clock = pygame.time.Clock()
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (70, 70, 70)
BLUE = (0, 128, 255)
GREEN = (0, 255, 0)
# Bone class
class Bone:
def __init__(self, start_pos, length, angle, parent=None):
self.start_pos = start_pos
self.length = length
self.angle = angle # in degrees
self.parent = parent
self.end_pos = self.calculate_end_pos()
self.dragging = False
def calculate_end_pos(self):
# Calculate the end position based on angle and length
rad = pygame.math.radians(self.angle)
dx = self.length * pygame.math.cos(rad)
dy = self.length * pygame.math.sin(rad)
return Vector2(self.start_pos.x + dx, self.start_pos.y + dy)
def update(self):
# Update start position based on parent's end position
if self.parent:
self.start_pos = self.parent.end_pos
self.end_pos = self.calculate_end_pos()
def draw(self, surface):
# Draw the bone
pygame.draw.line(surface, WHITE, self.start_pos, self.end_pos, 3)
# Draw the joint
pygame.draw.circle(surface, BLUE if self.dragging else WHITE, self.end_pos, 5)
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if (self.end_pos - event.pos).length() < 10:
self.dragging = True
elif event.type == pygame.MOUSEBUTTONUP:
if self.dragging:
self.dragging = False
elif event.type == pygame.MOUSEMOTION:
if self.dragging:
mouse_pos = Vector2(event.pos)
direction = mouse_pos - self.start_pos
self.angle = pygame.math.degrees(direction.as_polar()[1])
self.update()
# Timeline class
class Timeline:
def __init__(self):
self.keyframes = []
self.playing = False
self.current_frame = 0
self.total_frames = 300 # Total number of frames in the timeline
self.rect = pygame.Rect(0, HEIGHT - TIMELINE_HEIGHT, WIDTH, TIMELINE_HEIGHT)
def add_keyframe(self, frame, bones_state):
self.keyframes.append((frame, bones_state))
self.keyframes.sort(key=lambda x: x[0]) # Sort keyframes based on frame
def update(self):
if self.playing:
self.current_frame += 1
if self.current_frame > self.total_frames:
self.current_frame = 0 # Loop back to the start
def draw(self, surface):
# Draw the timeline background
pygame.draw.rect(surface, GRAY, self.rect)
# Draw keyframes
for frame, _ in self.keyframes:
x = (frame / self.total_frames) * WIDTH
pygame.draw.line(surface, GREEN, (x, HEIGHT - TIMELINE_HEIGHT), (x, HEIGHT), 2)
# Draw the playhead
playhead_x = (self.current_frame / self.total_frames) * WIDTH
pygame.draw.line(surface, WHITE, (playhead_x, HEIGHT - TIMELINE_HEIGHT), (playhead_x, HEIGHT), 2)
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.playing = not self.playing
# Main function
def main():
# Create bones for the stickman
pelvis = Bone(Vector2(WIDTH / 2, HEIGHT / 2), 50, 90)
torso = Bone(pelvis.end_pos, 100, 90, parent=pelvis)
head = Bone(torso.end_pos, 30, 90, parent=torso)
left_arm = Bone(torso.end_pos, 70, 60, parent=torso)
right_arm = Bone(torso.end_pos, 70, 120, parent=torso)
left_leg = Bone(pelvis.start_pos, 70, 110, parent=pelvis)
right_leg = Bone(pelvis.start_pos, 70, 70, parent=pelvis)
bones = [pelvis, torso, head, left_arm, right_arm, left_leg, right_leg]
# Create the timeline
timeline = Timeline()
# Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle events for bones
for bone in bones:
bone.handle_event(event)
# Handle events for timeline
timeline.handle_event(event)
# Add keyframe on 'K' press
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_k:
# Save current state of bones
bones_state = [bone.angle for bone in bones]
timeline.add_keyframe(timeline.current_frame, bones_state)
# Update bones
for bone in bones:
bone.update()
# Update timeline
timeline.update()
# If playing, update bones to match keyframes
if timeline.playing and len(timeline.keyframes) > 0:
# Find keyframes surrounding the current frame
prev_keyframe = None
next_keyframe = None
for keyframe in timeline.keyframes:
if keyframe[0] <= timeline.current_frame:
prev_keyframe = keyframe
elif keyframe[0] > timeline.current_frame:
next_keyframe = keyframe
break
if prev_keyframe and next_keyframe:
frame1, state1 = prev_keyframe
frame2, state2 = next_keyframe
t = (timeline.current_frame - frame1) / (frame2 - frame1)
for i, bone in enumerate(bones):
angle = state1[i] * (1 - t) + state2[i] * t
bone.angle = angle
bone.update()
elif prev_keyframe:
# Hold the last keyframe
_, state = prev_keyframe
for i, bone in enumerate(bones):
bone.angle = state[i]
bone.update()
# Fill background
screen.fill(BLACK)
# Draw bones
for bone in bones:
bone.draw(screen)
# Draw timeline
timeline.draw(screen)
# Update display
pygame.display.flip()
# Cap the frame rate at 60 FPS
clock.tick(60)
if __name__ == "__main__":
main()
How to Use the Program
Run the Program: Save the code in a file named stickman_animator.py and run it using:
bash
python stickman_animator.py
Manipulate the Stickman:
Click and Drag the blue joints (endpoints of the bones) to move the stickman's limbs.
The stickman's pose will update as you drag the joints.
Add Keyframes:
Press 'K' to add a keyframe at the current frame in the timeline.
Keyframes are represented by green lines in the timeline at the bottom of the screen.
Play/Pause Animation:
Press Spacebar to toggle between playing and pausing the animation.
When playing, the stickman's pose will interpolate smoothly between keyframes.
Reset Animation:
Press 'R' (if implemented) to reset the timeline and keyframes.
Understanding the Code
Bone Class:
Represents each segment of the stickman.
Contains methods to calculate positions, draw the bone, and handle mouse events for dragging.
Timeline Class:
Manages keyframes and animation playback.
Handles adding keyframes and updating the current frame during playback.
Main Function:
Initializes the bones to create the stickman.
Runs the main loop to handle events, update the animation, and render the visuals.
Notes
Simplifications:
This is a basic implementation meant for educational purposes.
The stickman is a simple structure without advanced features like inverse kinematics.
Extending the Program:
You can add more features such as saving/loading animations, adding more bones, or implementing a GUI for better interaction.
Error Handling:
The code assumes valid input and interactions. Additional error handling can be added for robustness.
Sample Output
When you run the program, you should see a window like this:
Note: Replace the link above with an actual screenshot if desired.
Conclusion
This program provides a basic framework for animating a stickman by manipulating bones and recording keyframes. It's a starting point for exploring more complex animation concepts and building more sophisticated animation tools.
Feel free to experiment with the code and add new features!
Let me know if you have any questions or need further assistance!