## Introduction You're standing on a cliff, watching a medieval trebuchet launch stones across a valley. The operator adjusts the counterweight, changes the release angle, and modifies the throwing arm length. Each shot follows a predictable mathematical path, yet hitting the target requires understanding the relationship between initial conditions and final impact point. This same physics governs everything from basketball shots to artillery fire to spacecraft trajectories. The mathematics is elegant: a quadratic equation in time determines when the projectile hits the ground, while trigonometry governs the horizontal distance traveled. This project takes you from deriving these fundamental equations to building an interactive game with AI assistance, revealing how mathematical models become engaging user experiences. ## Project Description Starting with the physics of projectile motion, you'll derive and implement the mathematical model from first principles. Then you'll transform your calculation into a text-based targeting game. Finally, using AI collaboration, you'll add animation and a feature of your own design. **1 Point - Foundation**: Derive the projectile motion equations from physics principles and implement a targeting game where players adjust launch parameters to hit randomly placed targets. Master the mathematical relationships between initial velocity, angle, height, and impact distance. **2 Points - Exploration**: Use AI assistance to add animation to your game, then design and implement an additional feature. Document your AI collaboration strategy, including effective prompting techniques and the iterative development process. **Key Deliverable**: A complete interactive physics simulation demonstrating both mathematical modeling skills and effective human-AI collaboration in scientific computing. ## Mathematical Background: From Physics to Equations ### The Physics Foundation A projectile launched with initial velocity $v_0$ at angle $\theta$ from height $h_0$ follows these kinematic principles: **Horizontal Motion**: $x(t) = v_0 \cos(\theta) \cdot t$ **Vertical Motion**: $y(t) = h_0 + v_0 \sin(\theta) \cdot t - \frac{1}{2}gt^2$ **Check Your Understanding**: Why is there no acceleration term in the horizontal equation? What assumptions about air resistance are we making? The projectile hits the ground when $y(t) = 0$, giving us: $-\frac{1}{2}gt^2 + v_0 \sin(\theta) \cdot t + h_0 = 0$ This quadratic equation in time has the form $at^2 + bt + c = 0$ where: - $a = -\frac{g}{2} = -4.905$ - $b = v_0 \sin(\theta)$ - $c = h_0$ ## Implementation Guidelines ### Part 1: Foundation - Mathematical Modeling and Game Mechanics (1 Point) #### Step 1: Deriving the Quadratic Formula Implementation **Check Your Understanding**: Before implementing, work out by hand: if you launch a projectile from 10m height at 45° with 20 m/s initial velocity, what quadratic equation determines the impact time? **Your Task**: Build the mathematical foundation by implementing a quadratic solver. **MATLAB:** ```matlab function [r1, r2] = solveQuadratic(a, b, c) % Solve quadratic equation ax^2 + bx + c = 0 % YOUR CODE HERE: Implement the quadratic formula discriminant = ____; % b^2 - 4ac if discriminant < 0 error('No real solutions - projectile never hits ground!'); end r1 = ____; % (-b + sqrt(discriminant)) / (2*a) r2 = ____; % (-b - sqrt(discriminant)) / (2*a) end % Test your implementation a = -4.905; b = 20*sin(pi/4); c = 10; [t1, t2] = solveQuadratic(a, b, c); fprintf('Impact times: t1=%.3f, t2=%.3f seconds\n', t1, t2); ``` **Python:** ```python import numpy as np def solve_quadratic(a, b, c): """Solve quadratic equation ax^2 + bx + c = 0""" # YOUR CODE HERE: Implement the quadratic formula discriminant = ____ # b**2 - 4*a*c if discriminant < 0: raise ValueError('No real solutions - projectile never hits ground!') r1 = ____ # (-b + np.sqrt(discriminant)) / (2*a) r2 = ____ # (-b - np.sqrt(discriminant)) / (2*a) return r1, r2 # Test your implementation a = -4.905 b = 20 * np.sin(np.pi/4) c = 10 t1, t2 = solve_quadratic(a, b, c) print(f'Impact times: t1={t1:.3f}, t2={t2:.3f} seconds') ``` **Verification**: Only one root should be positive (the physical impact time). Which root represents the actual impact? #### Step 2: Building the Projectile Distance Calculator **Your Task**: Combine the physics equations into a complete projectile analysis function. **MATLAB:** ```matlab function distance = calculateDistance(v0, theta_deg, h0) % Calculate horizontal distance traveled by projectile % Inputs: v0 (m/s), theta_deg (degrees), h0 (m) % Output: distance (m) g = 9.81; % m/s^2 theta = theta_deg * pi/180; % Convert to radians % Set up quadratic equation for impact time: y(t) = 0 % YOUR CODE HERE: Define coefficients for -g/2*t^2 + v0*sin(theta)*t + h0 = 0 a = ____; % Coefficient of t^2 b = ____; % Coefficient of t c = ____; % Constant term % Find impact time [t1, t2] = solveQuadratic(a, b, c); impact_time = max(t1, t2); % Take positive root % Calculate horizontal distance % YOUR CODE HERE: Use x(t) = v0*cos(theta)*t distance = ____; fprintf('Launch: v0=%.1f m/s, angle=%.1f°, height=%.1f m\n', v0, theta_deg, h0); fprintf('Impact time: %.2f seconds, Distance: %.1f meters\n', impact_time, distance); end % Test with known case dist = calculateDistance(20, 45, 10); ``` **Python:** ```python def calculate_distance(v0, theta_deg, h0): """Calculate horizontal distance traveled by projectile""" g = 9.81 # m/s^2 theta = np.radians(theta_deg) # Convert to radians # Set up quadratic equation for impact time: y(t) = 0 # YOUR CODE HERE: Define coefficients for -g/2*t^2 + v0*sin(theta)*t + h0 = 0 a = ____ # Coefficient of t^2 b = ____ # Coefficient of t c = ____ # Constant term # Find impact time t1, t2 = solve_quadratic(a, b, c) impact_time = max(t1, t2) # Take positive root # Calculate horizontal distance # YOUR CODE HERE: Use x(t) = v0*cos(theta)*t distance = ____ print(f'Launch: v0={v0:.1f} m/s, angle={theta_deg:.1f}°, height={h0:.1f} m') print(f'Impact time: {impact_time:.2f} seconds, Distance: {distance:.1f} meters') return distance # Test with known case dist = calculate_distance(20, 45, 10) ``` #### Step 3: Creating the Targeting Game **Check Your Understanding**: What makes a good targeting game? Should the target be very close (easy) or far away (challenging)? How should you handle player input validation? **Your Task**: Transform your physics calculation into an interactive game. **MATLAB:** ```matlab function playTargetingGame() % Interactive projectile targeting game fprintf('\n=== PROJECTILE TARGETING GAME ===\n'); fprintf('Hit the target by choosing velocity and angle!\n\n'); % Initialize game parameters h0 = input('Enter launch height (1-50 meters): '); % YOUR CODE HERE: Generate random target distance target_distance = ____; % Random value between 20 and 200 meters fprintf('Target is at %.1f meters. Good luck!\n\n', target_distance); max_attempts = 10; tolerance = 2.0; % Within 2 meters counts as hit for attempt = 1:max_attempts fprintf('--- Attempt %d/%d ---\n', attempt, max_attempts); % Get player inputs v0 = input('Initial velocity (5-100 m/s): '); theta = input('Launch angle (1-89 degrees): '); % Validate inputs if v0 < 5 || v0 > 100 || theta < 1 || theta > 89 fprintf('Invalid input! Try again.\n\n'); continue; end % Calculate shot distance shot_distance = calculateDistance(v0, theta, h0); % Check if hit error = abs(shot_distance - target_distance); % YOUR CODE HERE: Implement hit detection and feedback if error <= tolerance fprintf('\n*** HIT! *** You hit within %.1f meters!\n', error); fprintf('You won in %d attempts!\n', attempt); return; else if shot_distance < target_distance fprintf('Too short by %.1f meters. Increase velocity or angle.\n\n', target_distance - shot_distance); else fprintf('Too far by %.1f meters. Decrease velocity or angle.\n\n', shot_distance - target_distance); end end end fprintf('Game over! Target was at %.1f meters.\n', target_distance); end % Start the game playTargetingGame(); ``` **Python:** ```python import random def play_targeting_game(): """Interactive projectile targeting game""" print('\n=== PROJECTILE TARGETING GAME ===') print('Hit the target by choosing velocity and angle!\n') # Initialize game parameters h0 = float(input('Enter launch height (1-50 meters): ')) # YOUR CODE HERE: Generate random target distance target_distance = ____ # Random value between 20 and 200 meters print(f'Target is at {target_distance:.1f} meters. Good luck!\n') max_attempts = 10 tolerance = 2.0 # Within 2 meters counts as hit for attempt in range(1, max_attempts + 1): print(f'--- Attempt {attempt}/{max_attempts} ---') # Get player inputs try: v0 = float(input('Initial velocity (5-100 m/s): ')) theta = float(input('Launch angle (1-89 degrees): ')) except ValueError: print('Please enter valid numbers!\n') continue # Validate inputs if v0 < 5 or v0 > 100 or theta < 1 or theta > 89: print('Invalid input! Try again.\n') continue # Calculate shot distance shot_distance = calculate_distance(v0, theta, h0) # Check if hit error = abs(shot_distance - target_distance) # YOUR CODE HERE: Implement hit detection and feedback if error <= tolerance: print(f'\n*** HIT! *** You hit within {error:.1f} meters!') print(f'You won in {attempt} attempts!') return else: if shot_distance < target_distance: print(f'Too short by {target_distance - shot_distance:.1f} meters. Increase velocity or angle.\n') else: print(f'Too far by {shot_distance - target_distance:.1f} meters. Decrease velocity or angle.\n') print(f'Game over! Target was at {target_distance:.1f} meters.') # Start the game play_targeting_game() ``` **Verification**: Play your game several times. Can you consistently hit targets? What strategies work best for different target distances? ### Part 2: Exploration - AI-Assisted Development (2 Points) #### Step 4: Animation with AI Collaboration **Check Your Understanding**: Animation requires plotting projectile trajectories over time. What mathematical functions will you need? How should you structure the conversation with AI to get useful code? **Your Task**: Use the course AI chatbot to add animation to your game. Document your prompting strategy. **Recommended AI Interaction Strategy:** ``` Initial Prompt: "I have a working MATLAB projectile motion game where players enter velocity and angle to hit targets. The game currently just displays text results. I want to add animation showing the projectile trajectory. Here's my current calculateDistance function: [paste your code] Please help me create an animated trajectory plot that shows: 1. The projectile path as a curved line 2. The launch point and target position marked clearly 3. The projectile moving along the path over time Start with just the basic trajectory plotting first." ``` **Follow-up Prompts:** ``` "Great! Now can you modify it to show the projectile as a moving dot that travels along the path?" "Can you add the ground level, launch platform, and target marker to make it more visually clear?" "How can I integrate this animation into my existing game loop?" ``` **Your Documentation Task:** ```matlab % Document your AI interaction fprintf('=== AI COLLABORATION LOG ===\n'); fprintf('Prompts used:\n'); fprintf('1. [Record your initial prompt here]\n'); fprintf('2. [Record follow-up prompts]\n'); fprintf('3. [What worked well/poorly]\n'); fprintf('Iterations needed: [number]\n'); fprintf('Final result: [describe what you achieved]\n'); ``` #### Step 5: Feature Design and Implementation **Your Task**: Choose and implement one additional feature using AI assistance. Document your design process. **Possible Features:** - Multiple targets with scoring system - Wind effects (add horizontal acceleration) - Obstacle avoidance (barriers in the path) - Trajectory prediction (show path before firing) - Historical shot tracking (show previous attempts) - Power-up system (special shots) **Implementation Framework:** ```matlab function myCustomFeature() % YOUR CHOSEN FEATURE IMPLEMENTATION fprintf('Implementing feature: [Your feature name]\n'); % YOUR CODE HERE: Describe your feature in comments first % Example: "Wind system that adds random horizontal acceleration" % 1. Generate random wind speed and direction % 2. Modify trajectory equations to include wind acceleration % 3. Update animation to show wind effects % 4. Provide wind information to player end ``` **AI Collaboration Documentation:** ```matlab % Feature Development Log fprintf('=== FEATURE DEVELOPMENT ===\n'); fprintf('Chosen feature: [name]\n'); fprintf('Reason for choice: [why this feature]\n'); fprintf('AI prompting strategy: [how you approached it]\n'); fprintf('Challenges encountered: [what was difficult]\n'); fprintf('Final implementation: [what you achieved]\n'); ``` ## Analysis Framework ### Mathematical Insights - How does the quadratic formula connect to real-world physics problems? - What role does parameter sensitivity play in targeting accuracy? - How do different launch angles affect optimal strategies? ### AI Collaboration Analysis - What types of programming tasks does AI handle well vs. poorly? - How does iterative prompting compare to trying to get everything in one request? - What programming knowledge do you still need when working with AI assistants? ### Game Design and Physics - How do mathematical accuracy and gameplay enjoyment sometimes conflict? - What simplifying assumptions make the physics tractable but unrealistic? - How does user interface design affect understanding of mathematical relationships? ## Real-World Context Understanding projectile motion through interactive development connects to numerous applications: ### Military and Defense Applications - **[Artillery Calculations](https://en.wikipedia.org/wiki/External_ballistics)**: Historical and modern targeting systems - **[Missile Trajectory Planning](https://www.nasa.gov/centers/johnson/pdf/584722main_Wings-ch4c-pgs53-73.pdf)**: Optimal launch parameters for various missions ### Sports and Recreation - **[Basketball Shot Analysis](https://www.google.com/search?q=basketball+trajectory+physics+optimal+angle)**: Optimal shooting angles and velocities - **[Golf Ball Physics](https://en.wikipedia.org/wiki/Golf_ball#Aerodynamics)**: How dimples and spin affect projectile motion ### Space Exploration - **[Spacecraft Trajectories](https://www.nasa.gov/audience/forstudents/5-8/features/nasa-knows/what-is-orbital-mechanics-58.html)**: Launch windows and trajectory planning - **[Mars Rover Landing](https://www.jpl.nasa.gov/edu/learn/project/trajectory-and-navigation-of-a-mars-rover/)**: Atmospheric entry calculations The AI collaboration aspect reflects the growing importance of human-AI partnerships in scientific computing and engineering design. ## Deliverable Checklist - [ ] **Mathematical Foundation** - [ ] Hand-derived quadratic formula implementation with physics verification - [ ] Complete projectile distance calculator with proper input validation - [ ] Functional text-based targeting game with hit detection and feedback - [ ] Documentation of mathematical relationships between parameters and outcomes - [ ] **AI-Assisted Development** - [ ] Successful animation implementation using AI collaboration - [ ] Complete log of AI prompting strategy with effective and ineffective approaches - [ ] Analysis of AI capabilities and limitations in mathematical programming - [ ] Documentation of iterative development process and debugging with AI assistance - [ ] **Creative Feature Implementation** - [ ] Design and implementation of one additional game feature with AI help - [ ] Clear documentation of feature design rationale and implementation challenges - [ ] Analysis of how mathematical complexity affects both coding difficulty and gameplay - [ ] Reflection on the balance between mathematical accuracy and user experience - [ ] **Communication** - [ ] One-page synthesis connecting physics, programming, and AI collaboration - [ ] Five to seven minute video walkthrough demonstrating both the mathematical concepts and the AI development process - [ ] Clear explanation of how mathematical modeling enables interactive experiences and how AI assists in rapid prototyping