Luawe All pages

Raycasting

A raycast asks the level one question: going from here in a straight line, what is the first thing in the way? That one question is behind a shot that hits, a beam that stops at a wall, a guard that sees the character only when nothing stands between them, and a ball that bounces.

In Luawe it is one function, world:raycast: a question put to the world. This page says what it is given and what it gives back, and then builds those four things with it. Every script here can be put into an empty level and tried with F5.

What a ray is

A ray is a straight line with a start and an end. It is given as four numbers: where it starts, and how far it goes across and down from there.

-- From the place 2, 5: six tiles to the right, and none down.
local hit = world:raycast(2, 5, 6, 0)
NumberMeans
x, yWhere the ray starts, in tiles
dxHow far it goes across: over 0 is to the right, under 0 to the left
dyHow far it goes down: over 0 is down, under 0 is up (y grows downwards, as everywhere in a level)

The ray ends where those two numbers take it and looks no further. 6, 0 is a ray six tiles long. 3, 4 goes three across and four down, which makes it five tiles long.

Your first ray

This script puts up a wall and sends a ray from the character to the right, in every picture the game draws. A thin line shows the ray, so that it can be seen stopping at the wall.

-- Something to look at, so that this can be tried in an empty level:
-- a wall three tiles to the right.
things.new(cat.Kind.decoration, { centerX = camera.x + 3, centerY = camera.y, width = 0.5, height = 3, name = "wall" })

-- A thin line that shows the ray.
-- Its No hitbox child keeps rays from meeting the line itself.
local line = things.new(cat.Kind.decoration, { centerX = 0, centerY = 0, width = 1, height = 0.06 })
line:addChild(cat.Child.noHitbox)

const REACH = 6 -- how far the ray looks, in tiles

level.frame:connect(function()
    -- From the character, REACH tiles to the right:
    -- the first thing in the way, or nil.
    local hit = world:raycast(player.x, player.y, REACH, 0)
    -- The line is as long as the ray got: up to what it met, or all the way.
    local long = hit and hit.distance or REACH
    line.width = long
    line.x = player.x
    line.y = player.y - line.height / 2
end)

What to notice:

  • Move the character up and down past the end of the wall. Beside the wall the line stops at it; above and below it the line runs its full six tiles.
  • world:raycast gives nil when nothing is in the way. That is why the script says hit and hit.distance or REACH: reading hit.distance from a nil would stop the script.
  • level.frame happens once for every picture the game draws, so the line follows the character smoothly. Events has more about it.
  • The line is a thing too, and a ray would meet it. A thing with the No hitbox child is never met.

What comes back

When the ray meets something, world:raycast gives a table that says what, where and how.

WrittenIs
hit.thingThe thing the ray met
hit.distanceHow far along the ray that is, in tiles
hit.x, hit.yThe place where the ray met it
hit.normalX, hit.normalYWhich way the side it met faces
local hit = world:raycast(player.x, player.y, 6, 0)
if hit then
    print(hit.thing.name, hit.distance)
    print(hit.x, hit.y)
    print(hit.normalX, hit.normalY)
end

hit.thing is a thing like any other: hit.thing.name reads its name, hit.thing.alpha = 0.3 fades it, hit.thing:destroy() removes it.

The two normal numbers say which way the side faces that the ray ran into. A ray going to the right meets a wall on its left side, and that side faces left: normalX is -1 and normalY is 0. A ray coming down onto the top of something gets 0 and -1. They are what makes a ball bounce the right way, further down this page.

Which way, and how far

Straight across, straight up and down, or anything in between:

local x, y = player.x, player.y

world:raycast(x, y, 6, 0)  -- six tiles to the right
world:raycast(x, y, -6, 0) -- to the left
world:raycast(x, y, 0, -6) -- up
world:raycast(x, y, 0, 6)  -- down
world:raycast(x, y, 3, 4)  -- three across and four down

From one place to another. Take the start away from the end. The ray then ends exactly at the other place, so whatever it meets is between the two:

local door = things.find("door")
local dx, dy = door.centerX - player.x, door.centerY - player.y
local hit = world:raycast(player.x, player.y, dx, dy, { except = door })
if hit == nil then
    print("nothing between the character and the door")
end

By an angle. 0 degrees is to the right, 90 is down, 180 to the left and 270 up: clockwise, the way a thing's rotation counts.

local function rayAt(x, y, degrees, reach, options)
    local angle = math.rad(degrees)
    local dx, dy = math.cos(angle) * reach, math.sin(angle) * reach
    return world:raycast(x, y, dx, dy, options)
end

local hit = rayAt(player.x, player.y, 45, 8) -- down to the right, eight tiles
print(hit)

The way the character is going. player.velocityX and player.velocityY say how fast it moves across and down. Divided by player.speed they are one tile long, and can be made any length:

level.frame:connect(function()
    local speed = player.speed
    if speed > 0.1 then
        -- Three tiles ahead of the character.
        local dx, dy = player.velocityX / speed * 3, player.velocityY / speed * 3
        local ahead = world:raycast(player.x, player.y, dx, dy)
        if ahead then
            print(`heading for {ahead.thing.name}`)
        end
    end
end)

What counts

A ray meets blocks and decorations, unless it is told otherwise. A table of options as the last value says what counts.

OptionMeans
kind = cat.Kind.objectBlocks and decorations. This is what counts when nothing is said
kind = cat.Kind.hazardOnly what kills when it is touched
kind = cat.Kind.solidOnly walls: blocks whose effect is cat.TouchEffect.solid, the ones the character can't go through
kind = cat.Kind.floorPieces of floor
kind = cat.Kind.textTexts
kind = cat.Kind.anyAll of these
onlyOnly these: a thing, a name, or a list of things and names
exceptAll but these
local x, y = player.x, player.y

-- only what kills
local danger = world:raycast(x, y, 5, 0, { kind = cat.Kind.hazard })
-- only walls: what the character can't go through
local blocked = world:raycast(x, y, 5, 0, { kind = cat.Kind.solid })
-- only the things called wall
local wall = world:raycast(x, y, 5, 0, { only = "wall" })
-- everything but those
local past = world:raycast(x, y, 5, 0, { except = { "glass", "fog" } })
print(danger, blocked, wall, past)

Some things a ray never meets:

  • The character. It is not a thing. To know whether a line passes the character, work it out from player.x and player.y, or let a block do it: a block kills what touches it (the beam below does this).
  • A thing that is not there: one whose Visible box is unticked or that a script hid, one that has not appeared yet or is gone again, one that was destroyed.
  • A thing with the No hitbox child, and a text that is pinned to the screen.
  • The water. It is no thing. world:nearest can look for it: see Looking without a line, below.

Three more things to know:

  • A ray goes by hitboxes, as the game does when it asks whether the character touches something. A decoration's hitbox is its whole square. A block's is a little inside its edges (0.08 tiles), so a ray meets a block a little later than its picture begins. A wall's (a block whose effect is cat.TouchEffect.solid) is its whole rectangle, with nothing taken off. A thing's Hitbox rows change its hitbox for rays as well.
  • A ray that starts inside a thing meets that thing at once, with a distance of 0. A ray sent from a thing's own middle needs except with that thing in it, or it never gets out.
  • A new thing takes a moment to be there. A thing made with things.new can be met from the next step on, and a block, a decoration or a piece of floor pops in over a quarter of a beat first.

Can it see me?

A guard sees the character when nothing stands between the two. So: send a ray from the guard to the character, and see whether it meets anything.

-- Something to try it with, in an empty level: a guard, and a wall to hide behind.
local guard = things.new(cat.Kind.decoration, { centerX = camera.x + 4, centerY = camera.y, width = 0.8, height = 0.8 })
things.new(cat.Kind.decoration, { centerX = camera.x + 2, centerY = camera.y + 1, width = 0.4, height = 3, name = "wall" })

const SIGHT = 7 -- how far the guard sees, in tiles

level.frame:connect(function()
    local x, y = guard.centerX, guard.centerY
    local dx, dy = player.x - x, player.y - y
    local far = math.sqrt(dx * dx + dy * dy)
    -- A ray from the guard to the character. It ends at the character,
    -- so whatever it meets is in between.
    local sees = far <= SIGHT and world:raycast(x, y, dx, dy, { except = guard }) == nil
    -- Red when it sees the character, green when it does not.
    guard.color = sees and color.rgb(255, 70, 70) or color.rgb(80, 200, 120)
end)

What to notice:

  • The ray is exactly as long as the way to the character. Anything it meets is therefore between the two, and nothing behind the character can get in the way.
  • except = guard is needed because the ray starts in the guard's own middle. Without it the ray would meet the guard at once.
  • far <= SIGHT comes first. When the character is too far away the ray is never sent: and stops at the first thing that is false.

Try: let only walls block the view, with { only = "wall" }. Make the guard chase the character while it sees it: guard.x += dx / far * 2 * seconds in the same function (which is then given seconds).

A beam that stops at a wall

A laser beam goes on until something is in its way. The ray says how far that is, and the beam is made that long.

-- Something to try it with, in an empty level:
-- a wall that goes up and down through the beam's way.
local wall = things.new(cat.Kind.decoration, {
    centerX = camera.x + 3, centerY = camera.y - 2, width = 0.5, height = 1.5, name = "wall",
})

local fromX, fromY = camera.x - 4, camera.y - 2 -- where the beam starts
const REACH = 12 -- how far it goes when nothing stops it

-- The beam is a thin block. A block kills what touches it,
-- so the beam needs no code of its own for that.
local beam = things.new(cat.Kind.block, { x = fromX, centerY = fromY, width = 1, height = 0.4 })

level.frame:connect(function()
    -- Only walls stop it. Without `only` the ray would meet the beam itself:
    -- it starts inside it.
    local hit = world:raycast(fromX, fromY, REACH, 0, { only = "wall" })
    beam.width = hit and hit.distance or REACH
    beam.x = fromX
end)

while true do
    wall:tween({ y = wall.y + 3 }, 1.5, cat.Ease.sinusoidal, cat.Direction.inAndOut):wait()
    wall:tween({ y = wall.y - 3 }, 1.5, cat.Ease.sinusoidal, cat.Direction.inAndOut):wait()
end

What to notice:

  • The ray does the measuring and a thing does the showing. hit.distance is how far the beam got, and the beam's width is set to it.
  • only = "wall" keeps the ray to the things with that name. The beam lies along the ray, so a ray that counted everything would meet the beam first.
  • things.new is given the beam's left edge (x) and its middle from top to bottom (centerY): one of each is allowed. The beam grows to the right from fromX because its left edge is put back there in every picture.
  • The loop at the end moves the wall and waits for each glide to arrive. The beam grows and shrinks by itself, because the ray is sent again for every picture.

A beam that points any way needs its thing turned and put in place. This function lays a thin thing along a line, from x, y, going dx across and dy down:

local function lay(thing, x, y, dx, dy)
    local long = math.sqrt(dx * dx + dy * dy)
    thing.width = long
    thing.rotation = math.deg(math.atan(dy, dx))
    -- A thing turns round its middle, and its x and y are its left and top edges
    -- before it is turned.
    thing.x = x + dx / 2 - long / 2
    thing.y = y + dy / 2 - thing.height / 2
end

local beam = things.new(cat.Kind.block, { centerX = 0, centerY = 0, width = 1, height = 0.4 })
lay(beam, camera.x - 4, camera.y - 2, 5, 3)

Try: turn the beam like a lighthouse. Keep an angle, add to it in every picture (angle += 40 * seconds), send the ray that way with math.cos and math.sin as in Which way, and how far, and lay the beam along what the ray got.

A shot that looks before it moves

A fast shot does not glide: in every picture it is put a little further on. At 40 tiles a second that is most of a tile at a time, and a thin target can lie between two of its places without ever being touched. The shot would fly straight through.

A ray along the step closes that gap. Before the shot moves, it looks along the way it is about to go:

-- Something to shoot at, in an empty level: a thin target five tiles to the right.
things.new(cat.Kind.decoration, { centerX = camera.x + 5, centerY = camera.y, width = 0.2, height = 3, name = "target" })

const SPEED = 40 -- tiles a second

local shots = {}

-- A click of the mouse: a new shot where the character is.
input.mouseDown:connect(function()
    local shot = things.new(cat.Kind.decoration, { centerX = player.x, centerY = player.y, width = 0.25, height = 0.25 })
    table.insert(shots, shot)
end)

level.frame:connect(function(seconds)
    for i = #shots, 1, -1 do
        local shot = shots[i]
        local step = SPEED * seconds -- how far it goes in this picture
        -- Look along the step before taking it.
        local hit = world:raycast(shot.centerX, shot.centerY, step, 0, { only = "target" })
        if hit then
            print(`hit the {hit.thing.name}`)
            shot:destroy()
            table.remove(shots, i)
        elseif shot.centerX > camera.x + 12 then
            shot:destroy() -- far off to the right: gone
            table.remove(shots, i)
        else
            shot.x += step
        end
    end
end)

What to notice:

  • The ray is as long as one step, SPEED * seconds. Whatever lies between where the shot is and where it will be is found, however thin it is.
  • seconds is the time since the picture before. A speed times those seconds is how far to go now, so the shot is as fast on a slow computer as on a quick one.
  • The loop goes through the list backwards (#shots, 1, -1), so that taking a shot out does not skip the one after it.

Shoot the targets is a whole game built this way: shots in every direction, targets that burst, a score.

Bouncing

When a ray meets something, its normal says which way the side faces. A ball that hits that side goes on as if the side were a mirror.

-- Something to try it with, in an empty level:
-- four walls round the middle of the screen, and a ball.
local midX, midY = camera.x, camera.y
things.new(cat.Kind.decoration, { centerX = midX, centerY = midY - 3, width = 9.4, height = 0.4, name = "wall" })
things.new(cat.Kind.decoration, { centerX = midX, centerY = midY + 3, width = 9.4, height = 0.4, name = "wall" })
things.new(cat.Kind.decoration, { centerX = midX - 4.5, centerY = midY, width = 0.4, height = 6.4, name = "wall" })
things.new(cat.Kind.decoration, { centerX = midX + 4.5, centerY = midY, width = 0.4, height = 6.4, name = "wall" })
local ball = things.new(cat.Kind.decoration, { centerX = midX, centerY = midY, width = 0.4, height = 0.4 })

const HALF = 0.2      -- half the ball's width
local vx, vy = 5, 3.2 -- its speed across and down, in tiles a second

level.frame:connect(function(seconds)
    local speed = math.sqrt(vx * vx + vy * vy)
    local wayX, wayY = vx / speed, vy / speed -- the way it is going, one tile long
    local step = speed * seconds               -- how far it goes in this picture
    -- Look the way the ball is going, a tile further than its step.
    local look = step + 1
    local hit = world:raycast(ball.centerX, ball.centerY, wayX * look, wayY * look, { only = "wall" })
    -- How far the ball's middle would be from the side it is heading for,
    -- once this step is taken.
    local gap = hit and (hit.distance - step) * -(wayX * hit.normalX + wayY * hit.normalY)
    if gap and gap <= HALF then
        -- Its edge would be in the wall. It turns round instead:
        -- the speed it has into that side, taken away twice.
        local into = vx * hit.normalX + vy * hit.normalY
        vx -= 2 * into * hit.normalX
        vy -= 2 * into * hit.normalY
    else
        ball.x += vx * seconds
        ball.y += vy * seconds
    end
end)

What to notice:

  • The ray looks further than the ball moves. A ball has a size: its edge reaches a wall before its middle does. So the ray looks a tile ahead, and the script works out from what comes back whether the ball would touch.
  • gap is how far the ball's middle would be from the wall's side after this step. hit.distance - step is what is left of the way to the wall along the ray, and the normal turns that into the distance straight out from the side. A ball that comes in at a slant has further to go along its way than it is from the wall.
  • The bounce is three lines. into is how much of the ball's speed points into the side. Taking twice that away, along the normal, leaves the ball going away from the wall as fast as it came.
  • Against the wall on the right the normal is -1, 0, so only vx changes its sign. Against the top and the bottom only vy does. The same lines do a slanted wall, with no sums of your own.
  • In a picture with a bounce the ball stays where it is and only turns. It moves on in the next one.

Try: make it quicker with every bounce (vx *= 1.05 and the same for vy). Turn one wall by 20 degrees (rotation = 20 in its table) and watch the ball come off it at an angle.

Looking without a line

A ray looks along a line. For other questions there are other looks, and they take the same options (kind, only, except):

To knowAsk
What is nearest to a place, and how far awayworld:nearest(x, y, options)
How far it is to the water, the floor's edgeworld:nearest(x, y, { kind = cat.Kind.water })
Everything within a distance of a placeworld:thingsInCircle(x, y, radius, options)
Everything in a box (rotation in the options turns it)world:thingsInBox(x, y, width, height, options)
Everything that touches a thingworld:thingsIn(thing, options)
-- The nearest thing that kills, no further than four tiles away.
local near = world:nearest(player.x, player.y, { kind = cat.Kind.hazard, within = 4 })
if near then
    print(near.thing.name, near.distance, near.x, near.y)
end

-- Every thing called coin within three tiles of the character.
for _, coin in world:thingsInCircle(player.x, player.y, 3, { only = "coin" }) do
    coin:destroy()
end

world:nearest gives a table with thing, distance, and x, y (the place of the thing that is nearest), or nil. The three thingsIn looks give a list, which is empty when nothing is there. For the water the table has no thing, since water is none.

A close call uses world:nearest for hazards and for the water. Things, the character and the camera has all of the options in one table.

What it costs

A ray looks at every thing of the kinds it counts, one after the other. So a ray costs more in a level that has more in it, and a long ray costs the same as a short one.

A few dozen rays in every picture are nothing. Thousands are too many: a script has an allowance of work, and one that uses it up runs behind or is stopped (Limits and safety says how). Three habits keep a script far away from that:

  • Ask once and keep the answer. A ray's result in a local can be read as often as needed.
  • Ask for less. kind = cat.Kind.hazard looks at fewer things than a ray that counts every object.
  • Use the look that fits. One world:nearest or world:thingsInCircle does what a fan of rays does badly.

When a ray finds nothing

A ray that gives nil when it should have met something is nearly always one of these:

  1. The last two numbers were meant as a place. They are how far to go: toX - x, toY - y.
  2. Up and down are mixed up. y grows downwards, so up is under 0.
  3. The thing's kind does not count. Floor and texts are met only with kind = cat.Kind.floor, cat.Kind.text or cat.Kind.any.
  4. The thing is not there yet, or not any more: made in this very step, still popping in, switched off with Visible, or destroyed.
  5. The thing has no hitbox: a No hitbox child, or a hitbox made smaller than the thing.
  6. The name is not quite the same. only = "wall" meets only things called exactly wall: Wall is another name.

And a ray that meets the wrong thing, at a distance of 0:

  1. It starts inside a thing: often the thing that sends it. Use except.
  2. It meets the line that was put there to show it. Give the line a No hitbox child.
  3. It counts the floor, and starts on it. Leave kind at objects, or use only.

When in doubt, show the ray: the line from Your first ray takes five lines and settles most questions at a glance.

Everything world:raycast and the other looks take and give is in the reference: world, what world:raycast gives and what world:nearest gives.

Next: scripts working together.