TGC Codebase Backup



Automatic sliding sprite collision by Code Dragon

27th Dec 2006 7:39
Summary

Performs sliding collision between sprites



Description

Call resolve_spr_collision(moveable, stationary) to resolve sprite collision. moveable is the sprite that's allowed to move (a character) and stationary is the sprite that's not allowed to move (a wall). This function will do sliding collision on the sprites, no matter what shape they're in. (This doesn't support collision resolution for transparent pixels, it will treat all sprites as rectangles or squares)



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    sync on
sync rate 0

box 0, 0, 64, 64
get image 1, 0, 0, 32, 64
get image 2, 0, 0, 63, 32

sprite 1, 0, 0, 1
sprite 2, 100, 100, 2

do
  sprite 1, sprite x(1) + rightkey() - leftkey(), sprite y(1) + downkey() - upkey(), 1
  resolve_spr_collision(1, 2)
  sync
loop

function resolve_spr_collision(moveable as dword, stationary as dword)

  if sprite collision(moveable, stationary) = 0 then exitfunction

  local move_x as dword
  local move_y as dword
  local stat_x as dword
  local stat_y as dword

  move_x = sprite x(moveable) + sprite width(moveable) / 2
  move_y = sprite y(moveable) + sprite height(moveable) / 2
  stat_x = sprite x(stationary) + sprite width(stationary) / 2
  stat_y = sprite y(stationary) + sprite height(stationary) / 2

  if move_x > stat_x
    reso_x = (sprite x(stationary) + sprite width(stationary)) - (sprite x(moveable))
  else
    reso_x = (sprite x(stationary)) - (sprite x(moveable) + sprite width(moveable))
  endif

  if move_y > stat_y
    reso_y = (sprite y(stationary) + sprite height(stationary)) - (sprite y(moveable))
  else
    reso_y = (sprite y(stationary)) - (sprite y(moveable) + sprite height(moveable))
  endif

  if abs(reso_x) > abs(reso_y)
    reso_x = 0
  else
    reso_y = 0
  endif

  sprite moveable, sprite x(moveable) + reso_x, sprite y(moveable) + reso_y, sprite image(moveable)

endfunction