;; ------------------------------------------------------------------------------------ ;; dan's cannon simulation ;; TODO: add realistic sound effects ;; ------------------------------------------------------------------------------------ (define-struct obj (x y vx vy)) (define WORLDX 700) (define WORLDY 350) (define g -10) ;; a gross estimate ;; ------------------------------------------------------------------------------------ ;; draw-obj : (make-obj x y vx vy) symbol -> boolean ;; paint a cannonball (define (draw-obj o color) (draw-solid-disk (make-posn (obj-x o) (- WORLDY (obj-y o))) ;; upside down 8 color)) ;; ------------------------------------------------------------------------------------ ;; launch : number number symbol -> boolean ;; provides a convenient way to launch a cannonball at a given angle (in degrees) and ;; speed (in meters per second) from (0,0) (define (launch angle speed color) (local ((define x0 0) (define y0 0) (define rads (* 2 pi (/ angle 360.0))) (define vx0 (* speed (cos rads))) (define vy0 (* speed (sin rads)))) (and (draw-solid-line (make-posn x0 (- WORLDY y0)) (make-posn (+ x0 (* 5 vx0)) (- WORLDY (+ y0 (* 5 vy0)))) color) (sim (make-obj x0 y0 vx0 vy0) color)))) ;; ------------------------------------------------------------------------------------ ;; sim : (make-obj x y vx vy) symbol -> boolean ;; simulates the motion of the given object in the xy-plane, given the ;; constant nagging influence of gravity in the y-direction. ;; simulation will stop when the object hits the ground. (define (sim o color) (cond [(< (obj-y o) 0) ; we're done. print to the display where the cannonball hit the ground (roughly) (draw-solid-string (make-posn (obj-x o) (- WORLDY 10)) (format "x = ~a m" (inexact->exact (round (obj-x o)))))] [else ; keep simulating. (and (sleep-for-a-while 0.1) (draw-obj o color) (sim (make-obj ; x1 = x0 + vx0 ; y1 = y0 + vy0 (+ (obj-x o) (obj-vx o)) (+ (obj-y o) (obj-vy o)) ; vx1 = vx0 + accel_x ; vy1 = vy0 + accel_y (obj-vx o) (+ (obj-vy o) g)) color))])) ;; ------------------------------------------------------------------------------------ ;; fire at will! (start WORLDX WORLDY) (wait-for-mouse-click) (launch 45 70 'black) (wait-for-mouse-click) (launch 60 70 'blue) ;(wait-for-mouse-click) ;(launch 45 35 'red)