Scripts:Stop slice on wall collision

From OHRRPGCE-Wiki
Jump to navigation Jump to search

If you're using "move slice by", not "move slice to", you can use the following script to check whether the slice is going to collide with the map's walls. If so it moves it to the collision point, stops it, and returns true. Note that if the slice does not collide then it won't move yet ("move slice by/to" move slices *after* scripts run, so you won't see where the slice is going to be this frame).

# Check for collision of sl with map walls. sl is a slice with velocity set by "move slice by"
# Returns true if the slice hit a wall and was stopped, otherwise this script does nothing so normal velocity will apply.
script, stop slice on wall collision, sl, begin
  variable (oldX, oldY, velX, velY)
  oldX := slice X (sl)
  oldY := slice Y (sl)
  velX := get slice velocity x (sl)
  velY := get slice velocity y (sl)
  if (move slice with wallchecking (sl, velX, velY) == 0) then (
    # No collision. Undo the movement, so normal velocity will apply.
    put slice (sl, oldX, oldY)
    return (false)
  ) else (
    stop slice (sl)
    return (true)
  )
end

If your slice is a projective and you want it to collide with walls you may want it to have a 1x1 hitbox so that at the moment of collision it's centered onto the wall edge rather than in front of it. This variant gives the slice a 1x1 hitbox:

# Check for collision of sl with map walls. sl is a slice with velocity set by "move slice by"
# Treats the slice as a 1x1 hitbox (probably its Horizontal/Vertical Anchor should be edge:center)
# Returns true if the slice hit a wall and was stopped, otherwise this script does nothing so normal velocity will apply.
script, stop 1x1 slice on wall collision, sl, begin
  variable (x, y, velX, velY, moveX, moveY)
  # The position of the slice's anchor point on the map
  x := slice screen x (sl) + camera pixel x
  y := slice screen y (sl) + camera pixel y
  velX := get slice velocity x (sl)
  velY := get slice velocity y (sl)
  # How far the slice can move without (or before a) collision.
  moveX := check wall collision x (x, y, 1, 1, velX, velY)
  moveY := check wall collision y (x, y, 1, 1, velX, velY)

  if (velX == moveX && velY == moveY) then (
    # No collision. Normal velocity will apply.
    return (false)
  ) else (
    # Move the slice to the collision point
    put slice (sl, slice x (sl) + moveX, slice y (sl) + moveY)
    stop slice (sl)
    return (true)
  )
end