Posted: 19th Sep 2013 7:23
I was thrilled when I first discovered that AppGameKit supported sprite clipping (scissor). I always wished DB had such a function. Tonight, I thought to myself, why couldn't it be created?

By resizing the sprite and manipulating its UV data, it is possible. It does have limitations, however, such as if the sprite you want to clip has already changed its size from default or uses an offset. In that case, you would have to adapt the function to retrieve the proper default size dimensions elsewhere (you'd have to keep track manually)

+ Code Snippet
REM ******************************************
REM Project: Sprite Clipping
REM Author:  Phaelax
REM Created: Wednesday, September 18, 2013
REM ******************************************


rem make a test image
box 1, 1, 400, 400, rgb(255,255,0),rgb(0,0,255),rgb(0,255,0),rgb(255,0,0)
get image 1, 1, 1, 400, 400

rem create a sprite
sprite 1, x, y, 1


sync on

do
      cls
      x = mousex()-200
      y = mousey()-200
      sprite 1, x, y, 1

      clipSprite(1, 200,200,500,500)
      
            
      outline(199,199,500,500)

      print screen fps()
      sync
loop



function clipSprite(id, x1, y1, x2, y2)
      rem get sprite's original dimensions
      img = sprite image(id)
      w = image width(img)
      h = image height(img)
      rem sprite's current position
      x = sprite x(id)
      y = sprite y(id)
      
      rem offsets
      ox = 0
      oy = 0
      
      rem top of sprite
      if y < y1
            h1 = y1 - y
            oy = -(y1-y)
      endif
      rem bottom of sprite
      if y+h > y2
            h2 = (y+h) - y2
      endif
      rem left side of sprite
      if x < x1
            w1 = x1 - x
            ox = -(x1-x)
      endif
      rem right side of sprite
      if x+w > x2
            w2 = (x+w) - x2
      endif
      
      rem calculate new size of sprite
      newHeight = h - h1 - h2
      av# = h1 / (h+0.0)
      bv# = 1 - h2 / (h+0.0)
      newWidth = w - w1 - w2
      au# = w1 / (w+0.0)
      bu# = 1 - w2 / (w+0.0)
      
      rem sprite size cannot be <= 0
      if newWidth > 0 and newHeight > 0
            rem update sprite texture coords
            set sprite texture coord 1, 0, au#, av#
            set sprite texture coord 1, 1, bu#, av#
            set sprite texture coord 1, 2, au#, bv#
            set sprite texture coord 1, 3, bu#, bv#
            rem resize sprite
            size sprite id, newWidth, newHeight
            offset sprite id, ox, oy
            show sprite id
      else
            hide sprite id
      endif
endfunction



function outline(x1, y1, x2, y2)
      line x1, y1, x2, y1
      line x1, y2, x2, y2
      line x1, y1, x1, y2
      line x2, y1, x2, y2
endfunction
Posted: 28th Sep 2013 13:05
Nice and useful as always. Thanks for sharing.