38. Shooting gallery (part 2)
In this post, I’ll add a zoom feature to my scope sights. In other words, the screen under the sights will enlarge the screen underneath by 2-5 times.
How do you include a zoom? This is is what I did.
- I drew the background image (targets etc) on an image instead of on the screen [1]
- I drew the previous shot marks on that image as well [2]
- I created an empty image the same size as the image for my sights
- I drew the background image onto it, multiplied by the zoom factor [3][4]
- I drew the scope image on top of that
- I drew the background on the screen
- I drew my zoomed image on the screen[5]
.
[1] This is because I’m going to have to draw it twice, as you will see below
[2] because I want to see shot marks when I zoom in
[3] so if the zoom is 3, I set the sprite width as 3 x the normal background width
[4] choosing x,y carefully so the right part of the background appears on the image
[5] this overlays the zoomed part of the image over the normal background
And this is the code required:
--make copy of background imgBack=backdrop:copy(0,0,backdrop.width,backdrop.height) setContext(imgBack) --draw past shots on screen for i,v in pairs(shots) do fill(shotColour) strokeWidth(0) ellipse(v.x,v.y,shotSize) end if aim.id>0 then --if aiming, draw scope and zoom local x,y=aim.x, aim.y+scopeBuffer --aiming point --zoom first --create new image to contain zoomed image and scope img=image(imgScope.width,imgScope.height) s=imgScope.width setContext(img) --draw on our copy pf the scope spriteMode(CORNER) --draw backdrop on our little image so it shows the bit we want --note zoom factor sprite(imgBack,-x*Zoom+s/2,-y*Zoom+s/2,Zoom*backdrop.width) --overlay the scope sprite(imgScope,0,0) setContext() --this is needed for some reason before we set it to a different image setContext(imgBack) --now draw our zoom image onto the background copy spriteMode(CENTER) sprite(img,x,y) end setContext() spriteMode(CORNER) sprite(imgBack,0,0) --draw the background copy with everything on it
And here is all the code.
PS I would have liked to make the zoom area circular, like the scope, but I couldn’t think of a way to do it.