@hilaloytun has joined the channel
Hello all, I have a problem with world program. [on-mouse mouse-event-handler] in big-bang causes error: “place-image: expects a real number as second argument, given #<image>”
(define (mouse-event-handler cw x y me) (cond [(mouse=? me “button-down”) (place-image IMG x CAR-Y BACKGROUND)] [else cw]))
Could you help why is it happening?
This is the main function: (define (main ws) (big-bang ws [on-tick tock] [to-draw render] [on-mouse mouse-event-handler] [on-key handle-key] [stop-when gone])) helpers: (define (render cw) (place-image IMG cw CAR-Y BACKGROUND)) (define (gone cw) (= cw (- BACKGROUND-W 10))) (define (handle-key c ke) (cond [(key=? ke " ") 0] [else c])) (define (mouse-event-handler cw x y me) (cond [(mouse=? me “button-down”) (place-image IMG x CAR-Y BACKGROUND)] [else cw]))
The second problem I get is; If I press a key during animation, it doesn’t execute the “stop-when step”(which is [stop-when gone]). If I leave the animation alone, don’t touch the keys, it executes the “stop-when” step.
The place-image
issue seems to be with render
where the second argument shouldn’t be cw
Thank you very much; I think I am missing something, since “cw” is supposed to the the “x position” of the image.
That’s not how it’s used in mouse-event, where according to the docs the first argument to the mouse-event handler must be the world state: https://docs.racket-lang.org/teachpack/2htdpuniverse.html#%28form._world._%28%28lib._2htdp%2Funiverse..rkt%29._on-mouse%29%29
FWIW cw
stands for “current world” (at least that’s my guess).
yes, cw is “current world” (the x point on the scene, where the image’s center pixel is located)
Ah! Your world consists only of that x-coordinate?
the animation on the scene is dynamic only on the x- coordinate, there’s a linear movement.
But mouse-event-handler
returns an image instead of a coordinate
on “button-down”
Laurent is right. The idea is that the mouse handler computes a new world state. Then later, render
will draw an image for that world state.
so, wherever I click on the scene, only x-position should be changed, y stays the same.
Your immediate problem is how to keep track of both the x-coordinate and whether the mouse was clicked or not. You most likely want to change your world state to a struct that has two fields: one for the x-coordinate and one for mouse information.
@hilaloytun You need to make sure that mouse-event-handler
returns an x-coordinate in all branches of your cond
ah, ok, I now understand, (not the solution, but the problem itself). thank you.