I script Roblox games.
I’m sqpxcy, 19, from Germany. Mostly server‑side Luau, plus the music and clothing for my own projects.
Scripting
Server-first Luau from my public repo, opens in a new tab. Pick a system and read the actual code.
--!strict
local Players = game:GetService("Players")
local Rewind = require(script.Parent.Rewind)
export type Hit = {
player: Player,
humanoid: Humanoid,
position: Vector3,
distance: number,
headshot: boolean,
}
local HEAD_SIZE = Vector3.new(1.6, 1.6, 1.6)
local BODY_SIZE = Vector3.new(2.4, 4.2, 1.8)
local BODY_OFFSET = CFrame.new(0, 0.1, 0)
local WALL_EPSILON = 0.25
local HitDetection = {}
local function slab(origin: number, direction: number, half: number, near: number, far: number): (number, number)
if math.abs(direction) < 1e-6 then
if math.abs(origin) > half then
return 1, -1
end
return near, far
end
local inverse = 1 / direction
local first = (-half - origin) * inverse
local second = (half - origin) * inverse
if first > second then
first, second = second, first
end
return math.max(near, first), math.min(far, second)
end
local function rayBox(origin: Vector3, direction: Vector3, frame: CFrame, size: Vector3): number?
local localOrigin = frame:PointToObjectSpace(origin)
local localDirection = frame:VectorToObjectSpace(direction)
local half = size * 0.5
local near, far = 0, math.huge
near, far = slab(localOrigin.X, localDirection.X, half.X, near, far)
near, far = slab(localOrigin.Y, localDirection.Y, half.Y, near, far)
near, far = slab(localOrigin.Z, localDirection.Z, half.Z, near, far)
if near > far then
return nil
end
return near
end
local function characterFilter(): { Instance }
local filter: { Instance } = {}
for _, player in Players:GetPlayers() do
local character = player.Character
if character then
table.insert(filter, character)
end
end
return filter
end
function HitDetection.cast(shooter: Player, origin: Vector3, direction: Vector3, range: number, timestamp: number): Hit?
local closest: Hit? = nil
for _, player in Players:GetPlayers() do
if player == shooter then
continue
end
local character = player.Character
local humanoid = if character then character:FindFirstChildOfClass("Humanoid") else nil
if humanoid == nil or humanoid.Health <= 0 then
continue
end
local snapshot = Rewind.at(player, timestamp)
if snapshot == nil then
continue
end
local toHead = rayBox(origin, direction, snapshot.head, HEAD_SIZE)
local toBody = rayBox(origin, direction, snapshot.root * BODY_OFFSET, BODY_SIZE)
local distance: number
local headshot: boolean
if toHead ~= nil and (toBody == nil or toHead <= toBody) then
distance, headshot = toHead, true
elseif toBody ~= nil then
distance, headshot = toBody, false
else
continue
end
if distance > range then
continue
end
if closest ~= nil and closest.distance <= distance then
continue
end
closest = {
player = player,
humanoid = humanoid,
position = origin + direction * distance,
distance = distance,
headshot = headshot,
}
end
return closest
end
function HitDetection.isBlocked(from: Vector3, to: Vector3): boolean
local offset = to - from
local distance = offset.Magnitude
if distance <= WALL_EPSILON then
return false
end
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = characterFilter()
params.IgnoreWater = true
local result = workspace:Raycast(from, offset, params)
return result ~= nil and result.Distance < distance - WALL_EPSILON
end
function HitDetection.castWorld(origin: Vector3, direction: Vector3, range: number): RaycastResult?
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = characterFilter()
params.IgnoreWater = true
return workspace:Raycast(origin, direction * range, params)
end
return HitDetection
--!strict
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
export type Snapshot = {
time: number,
root: CFrame,
head: CFrame,
}
local HISTORY_SECONDS = 1
local histories: { [Player]: { Snapshot } } = {}
local running = false
local Rewind = {}
local function capture()
local now = os.clock()
for _, player in Players:GetPlayers() do
local character = player.Character
if character == nil then
continue
end
local root = character:FindFirstChild("HumanoidRootPart") :: BasePart?
local head = character:FindFirstChild("Head") :: BasePart?
if root == nil or head == nil then
continue
end
local history = histories[player]
if history == nil then
history = {}
histories[player] = history
end
table.insert(history, {
time = now,
root = root.CFrame,
head = head.CFrame,
})
while #history > 1 and now - history[1].time > HISTORY_SECONDS do
table.remove(history, 1)
end
end
end
function Rewind.start()
if running then
return
end
running = true
RunService.Heartbeat:Connect(capture)
Players.PlayerRemoving:Connect(function(player)
histories[player] = nil
end)
end
function Rewind.forget(player: Player)
histories[player] = nil
end
function Rewind.at(player: Player, timestamp: number): Snapshot?
local history = histories[player]
if history == nil or #history == 0 then
return nil
end
local newest = history[#history]
if timestamp >= newest.time then
return newest
end
if timestamp <= history[1].time then
return history[1]
end
for index = #history, 2, -1 do
local older = history[index - 1]
if timestamp >= older.time then
local newer = history[index]
local span = newer.time - older.time
local alpha = if span > 0 then (timestamp - older.time) / span else 0
return {
time = timestamp,
root = older.root:Lerp(newer.root, alpha),
head = older.head:Lerp(newer.head, alpha),
}
end
end
return history[1]
end
return Rewind
--!strict
local Types = require(script.Parent.Types)
type WeaponConfig = Types.WeaponConfig
local Ballistics = {}
function Ballistics.fireInterval(config: WeaponConfig): number
return 60 / config.roundsPerMinute
end
function Ballistics.damageAt(config: WeaponConfig, distance: number): number
if distance <= config.falloffStart then
return config.damage
end
if distance >= config.falloffEnd then
return config.damage * config.falloffFloor
end
local alpha = (distance - config.falloffStart) / (config.falloffEnd - config.falloffStart)
return config.damage * (1 - alpha * (1 - config.falloffFloor))
end
function Ballistics.spreadAngle(config: WeaponConfig, bloom: number, aiming: boolean): number
local base = if aiming then config.spread.aim else config.spread.hip
return base + math.clamp(bloom, 0, config.spread.max)
end
function Ballistics.bloomAfterShot(config: WeaponConfig, bloom: number): number
return math.min(config.spread.max, bloom + config.spread.perShot)
end
function Ballistics.decayBloom(config: WeaponConfig, bloom: number, elapsed: number): number
return math.max(0, bloom - config.spread.decay * elapsed)
end
function Ballistics.coneDirection(direction: Vector3, angleDegrees: number, random: Random): Vector3
local forward = direction.Unit
if angleDegrees <= 0 then
return forward
end
local limit = math.rad(angleDegrees)
local azimuth = random:NextNumber() * math.pi * 2
local polar = math.acos(1 - random:NextNumber() * (1 - math.cos(limit)))
local offset =
Vector3.new(math.sin(polar) * math.cos(azimuth), math.sin(polar) * math.sin(azimuth), -math.cos(polar))
return CFrame.lookAlong(Vector3.zero, forward):VectorToWorldSpace(offset).Unit
end
return Ballistics
--!strict
export type Spring = {
impulse: (self: Spring, amount: Vector2) -> (),
step: (self: Spring, deltaTime: number) -> Vector2,
reset: (self: Spring) -> (),
}
local MAX_STEP = 1 / 120
local MAX_FRAME = 0.1
local function build(stiffness: number, damping: number): Spring
local position = Vector2.zero
local velocity = Vector2.zero
local spring: Spring
spring = {
impulse = function(_, amount)
velocity += amount
end,
step = function(_, deltaTime)
local remaining = math.min(deltaTime, MAX_FRAME)
while remaining > 0 do
local slice = math.min(remaining, MAX_STEP)
local acceleration = -stiffness * position - damping * velocity
velocity += acceleration * slice
position += velocity * slice
remaining -= slice
end
return position
end,
reset = function()
position = Vector2.zero
velocity = Vector2.zero
end,
}
return table.freeze(spring)
end
return {
new = build,
}
- Damage, spread, ammo and hits are resolved on the server
- Shots are checked against rewound hitboxes, so they land where the shooter saw the target
- Ray against oriented boxes, spring recoil and tracers on the client
--!strict
local Types = require(script.Parent.Types)
local SessionLock = {}
function SessionLock.stamp(jobId: string): Types.Lock
return {
jobId = jobId,
placeId = game.PlaceId,
heartbeat = os.time(),
}
end
function SessionLock.isOwnedBy(lock: Types.Lock?, jobId: string): boolean
return lock ~= nil and lock.jobId == jobId
end
function SessionLock.isExpired(lock: Types.Lock?, now: number, timeout: number): boolean
if lock == nil then
return true
end
return now - lock.heartbeat >= timeout
end
function SessionLock.blocks(lock: Types.Lock?, jobId: string, now: number, timeout: number): boolean
if lock == nil or lock.jobId == jobId then
return false
end
return not SessionLock.isExpired(lock, now, timeout)
end
return SessionLock
--!strict
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local Config = require(script.Parent.Config)
local MemoryBackend = require(script.Parent.MemoryBackend)
local Retry = require(script.Parent.Retry)
local Schema = require(script.Parent.Schema)
local SessionLock = require(script.Parent.SessionLock)
local Types = require(script.Parent.Types)
type Record = Types.Record
local JOB_ID = if game.JobId ~= "" then game.JobId else `studio-{os.time()}`
local backend: Types.Backend? = nil
local Store = {}
Store.jobId = JOB_ID
local function blankRecord(): Record
local now = os.time()
return {
version = Schema.VERSION,
data = Schema.template(),
lock = nil,
meta = {
created = now,
updated = now,
saves = 0,
placeVersion = game.PlaceVersion,
},
}
end
local function normalise(stored: Record): Record
local record = stored
if typeof(record.data) ~= "table" then
record.data = Schema.template()
end
if typeof(record.meta) ~= "table" then
local now = os.time()
record.meta = {
created = now,
updated = now,
saves = 0,
placeVersion = game.PlaceVersion,
}
end
record.version = tonumber(record.version) or 1
return record
end
local function apiAccessEnabled(): boolean
local ok = pcall(function()
DataStoreService:GetDataStore("DataServiceProbe"):GetAsync("probe")
end)
return ok
end
local function liveBackend(): Types.Backend
local dataStore = DataStoreService:GetDataStore(Config.storeName, Config.storeScope)
return table.freeze({
update = function(key: string, transform: (Record?) -> Record?): Record?
return dataStore:UpdateAsync(key, transform) :: Record?
end,
})
end
local function resolveBackend(): Types.Backend
local current = backend
if current then
return current
end
local created: Types.Backend
if Config.forceMemoryBackend or (RunService:IsStudio() and not apiAccessEnabled()) then
warn("[DataService] using the in memory backend, nothing written here survives the session")
created = MemoryBackend.new()
else
created = liveBackend()
end
backend = created
return created
end
local function waitForBudget()
if RunService:IsStudio() then
return
end
local deadline = os.clock() + Config.budgetTimeout
while DataStoreService:GetRequestBudgetForRequestType(Enum.DataStoreRequestType.UpdateAsync) < 1 do
if os.clock() >= deadline then
return
end
task.wait(1)
end
end
function Store.useBackend(replacement: Types.Backend)
backend = replacement
end
function Store.acquire(key: string): (boolean, Record?, string?, boolean)
local lastAttemptBlocked = false
local ok, record, message = Retry.attempt(Config.loadRetry, function(): Record
waitForBudget()
local blocked = false
local captured: Record? = nil
resolveBackend().update(key, function(stored: Record?): Record?
local current = if stored then normalise(stored) else blankRecord()
if SessionLock.blocks(current.lock, JOB_ID, os.time(), Config.lockTimeout) then
blocked = true
return nil
end
current.lock = SessionLock.stamp(JOB_ID)
captured = current
return current
end)
lastAttemptBlocked = blocked
if blocked then
error("the profile is locked by another server", 0)
end
return assert(captured, "UpdateAsync returned without running the transform")
end)
return ok, record, message, lastAttemptBlocked
end
function Store.commit(key: string, data: any, releaseLock: boolean): (boolean, string?, boolean)
local lockLost = false
local ok, _, message = Retry.attempt(Config.saveRetry, function(): boolean
waitForBudget()
local lost = false
resolveBackend().update(key, function(stored: Record?): Record?
local record = if stored then normalise(stored) else blankRecord()
if not SessionLock.isOwnedBy(record.lock, JOB_ID) then
lost = true
return nil
end
record.data = data
record.version = Schema.VERSION
record.meta.updated = os.time()
record.meta.saves += 1
record.meta.placeVersion = game.PlaceVersion
record.lock = if releaseLock then nil else SessionLock.stamp(JOB_ID)
return record
end)
if lost then
lockLost = true
Retry.fatal("the session lock was taken over by another server")
end
return true
end)
return ok, message, lockLost
end
return Store
--!strict
local Schema = require(script.Parent.Schema)
type Step = (data: any) -> ()
local STEPS: { [number]: Step } = {
[1] = function(data)
data.currency = {
coins = tonumber(data.coins) or 0,
gems = tonumber(data.gems) or 0,
}
data.coins = nil
data.gems = nil
end,
[2] = function(data)
local owned: { [string]: number } = {}
if typeof(data.pets) == "table" then
for _, petId in data.pets do
if typeof(petId) == "string" then
owned[petId] = (owned[petId] or 0) + 1
end
end
end
data.pets = {
owned = owned,
equipped = {},
}
end,
[3] = function(data)
local stats = if typeof(data.stats) == "table" then data.stats else {}
stats.playtimeSeconds = math.floor(tonumber(stats.playtime) or 0)
stats.playtime = nil
stats.bestRarity = if typeof(stats.bestRarity) == "string" then stats.bestRarity else "None"
data.stats = stats
end,
}
local Migrations = {}
function Migrations.run(data: any, from: number): (number, number)
local version = from
local applied = 0
while version < Schema.VERSION do
local step = STEPS[version]
if step == nil then
break
end
step(data)
version += 1
applied += 1
end
data.schemaVersion = version
return version, applied
end
return Migrations
--!strict
export type Options = {
attempts: number,
baseDelay: number,
maxDelay: number,
label: string,
}
type Fatal = {
fatal: boolean,
message: string,
}
local Retry = {}
function Retry.fatal(message: string)
error({ fatal = true, message = message }, 0)
end
function Retry.attempt<T>(options: Options, action: () -> T): (boolean, T?, string?)
local lastMessage: string? = nil
for tries = 1, options.attempts do
local ok, result = pcall(action)
if ok then
return true, result, nil
end
if typeof(result) == "table" and (result :: Fatal).fatal then
return false, nil, (result :: Fatal).message
end
lastMessage = tostring(result)
warn(`[{options.label}] attempt {tries} of {options.attempts} failed: {lastMessage}`)
if tries < options.attempts then
local backoff = math.min(options.maxDelay, options.baseDelay * 2 ^ (tries - 1))
task.wait(backoff * (0.75 + math.random() * 0.5))
end
end
return false, nil, lastMessage
end
return Retry
- The lock lives inside the record, so locking and loading is a single UpdateAsync
- Versioned data with schema migrations and retries with jittered backoff
- Falls back to an in-memory backend in Studio without API access
--!strict
export type Entry<T> = {
value: T,
weight: number,
}
export type Pool<T> = {
total: number,
sample: (self: Pool<T>, random: Random) -> T,
chanceOf: (self: Pool<T>, value: T) -> number,
}
local function build<T>(entries: { Entry<T> }): Pool<T>
assert(#entries > 0, "a weighted pool needs at least one entry")
local values: { T } = table.create(#entries)
local weights: { number } = table.create(#entries)
local cumulative: { number } = table.create(#entries)
local total = 0
for index, entry in entries do
assert(entry.weight > 0, "weights must be above zero")
total += entry.weight
values[index] = entry.value
weights[index] = entry.weight
cumulative[index] = total
end
local function lowerBound(target: number): number
local low, high = 1, #cumulative
while low < high do
local middle = (low + high) // 2
if cumulative[middle] < target then
low = middle + 1
else
high = middle
end
end
return low
end
local pool: Pool<T>
pool = {
total = total,
sample = function(_, random)
return values[lowerBound(random:NextNumber() * total)]
end,
chanceOf = function(_, value)
for index, candidate in values do
if candidate == value then
return weights[index] / total
end
end
return 0
end,
}
return table.freeze(pool)
end
return {
new = build,
}
--!strict
local Types = require(script.Parent.Types)
local INFLUENCE: { [Types.Rarity]: number } = {
Common = 0,
Uncommon = 0.35,
Legendary = 1,
}
local LuckCurve = {}
LuckCurve.MIN = 1
LuckCurve.MAX = 10
function LuckCurve.clamp(luck: number): number
if luck ~= luck then
return LuckCurve.MIN
end
return math.clamp(luck, LuckCurve.MIN, LuckCurve.MAX)
end
function LuckCurve.weightFor(definition: Types.PetDefinition, luck: number): number
local influence = INFLUENCE[definition.rarity]
return definition.weight * (1 + (LuckCurve.clamp(luck) - 1) * influence)
end
return LuckCurve
--!strict
export type Bucket = {
take: (self: Bucket, key: string) -> boolean,
retryAfter: (self: Bucket, key: string) -> number,
forget: (self: Bucket, key: string) -> (),
}
local function build(capacity: number, refillPerSecond: number): Bucket
assert(capacity > 0 and refillPerSecond > 0, "a bucket needs a positive capacity and refill rate")
local tokens: { [string]: number } = {}
local stamps: { [string]: number } = {}
local function refresh(key: string): number
local now = os.clock()
local last = stamps[key]
local available = tokens[key]
if last == nil or available == nil then
tokens[key] = capacity
stamps[key] = now
return capacity
end
available = math.min(capacity, available + (now - last) * refillPerSecond)
tokens[key] = available
stamps[key] = now
return available
end
local bucket: Bucket
bucket = {
take = function(_, key)
local available = refresh(key)
if available < 1 then
return false
end
tokens[key] = available - 1
return true
end,
retryAfter = function(_, key)
local missing = 1 - refresh(key)
if missing <= 0 then
return 0
end
return missing / refillPerSecond
end,
forget = function(_, key)
tokens[key] = nil
stamps[key] = nil
end,
}
return table.freeze(bucket)
end
return {
new = build,
}
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PetSystem = ReplicatedStorage:WaitForChild("PetSystem")
local LuckCurve = require(PetSystem:WaitForChild("LuckCurve"))
local PetRegistry = require(PetSystem:WaitForChild("PetRegistry"))
local Types = require(PetSystem:WaitForChild("Types"))
local WeightedPool = require(PetSystem:WaitForChild("WeightedPool"))
local RateLimiter = require(script.Parent:WaitForChild("RateLimiter"))
type PetDefinition = Types.PetDefinition
type Pool = WeightedPool.Pool<PetDefinition>
local BURST_SIZE = 5
local ROLLS_PER_SECOND = 3
local LUCK_PRECISION = 100
local pools: { [number]: Pool } = {}
local generators: { [Player]: Random? } = {}
local rollCounts: { [Player]: number } = {}
local luckValues: { [Player]: number } = {}
local limiter = RateLimiter.new(BURST_SIZE, ROLLS_PER_SECOND)
local rolled = Instance.new("BindableEvent")
local RollService = {}
RollService.enabled = true
RollService.rolled = rolled.Event
local function poolFor(luck: number): Pool
local quantised = math.round(LuckCurve.clamp(luck) * LUCK_PRECISION)
local cached = pools[quantised]
if cached then
return cached
end
local entries: { WeightedPool.Entry<PetDefinition> } = {}
for _, definition in PetRegistry.all() do
table.insert(entries, {
value = definition,
weight = LuckCurve.weightFor(definition, quantised / LUCK_PRECISION),
})
end
local pool = WeightedPool.new(entries)
pools[quantised] = pool
return pool
end
function RollService.bind(player: Player)
generators[player] = Random.new()
rollCounts[player] = rollCounts[player] or 0
luckValues[player] = luckValues[player] or LuckCurve.MIN
end
function RollService.unbind(player: Player)
generators[player] = nil
rollCounts[player] = nil
luckValues[player] = nil
limiter:forget(tostring(player.UserId))
end
function RollService.setLuck(player: Player, luck: number)
luckValues[player] = LuckCurve.clamp(luck)
end
function RollService.setRollCount(player: Player, count: number)
rollCounts[player] = math.max(0, math.floor(count))
end
function RollService.getRollCount(player: Player): number
return rollCounts[player] or 0
end
function RollService.odds(luck: number): { [string]: number }
local pool = poolFor(luck)
local chances: { [string]: number } = {}
for _, definition in PetRegistry.all() do
chances[definition.id] = pool:chanceOf(definition)
end
return chances
end
function RollService.roll(player: Player): Types.RollResponse
if not RollService.enabled then
return { ok = false, rejection = { code = "Disabled", retryAfter = 0 } }
end
local generator = generators[player]
if generator == nil then
return { ok = false, rejection = { code = "NotReady", retryAfter = 1 } }
end
local key = tostring(player.UserId)
if not limiter:take(key) then
return { ok = false, rejection = { code = "Cooldown", retryAfter = limiter:retryAfter(key) } }
end
local luck = luckValues[player] or LuckCurve.MIN
local pool = poolFor(luck)
local definition = pool:sample(generator)
local count = (rollCounts[player] or 0) + 1
rollCounts[player] = count
local result: Types.RollResult = {
petId = definition.id,
rarity = definition.rarity,
chance = pool:chanceOf(definition),
luck = luck,
rollNumber = count,
}
rolled:Fire(player, result)
return { ok = true, result = result }
end
return RollService
- Integer weights in a cached pool with binary-search sampling
- Luck only touches the rarer pets, per-rarity influence
- Token-bucket rate limit: bursts go through, autoclickers settle at 3 rolls per second
-- Discord: qvtey | Roblox: vrtaex
--!strict
--[[
BALLISTIC TURRET RANGE
A single server Script that builds and runs a complete firing range at runtime.
Why everything lives in one file and runs on the server:
the range is meant to be readable top to bottom, and keeping simulation on the server
means every player in the place watches the exact same shot instead of a client-side
guess. Nothing here depends on pre-built instances in the place - the script creates
its own targets, turrets and effects on start, so dropping it into ServerScriptService
is the whole installation.
How the pieces fit together:
Heartbeat -> fixed timestep accumulator
-> Target:step() moves targets on an analytic sine path
-> Turret:step() springs the aim vector towards a lead solution, fires on cooldown
-> Projectile:step() integrates gravity + quadratic drag + wind, raycasts the
segment it travelled this step, reports the hit back to the turret
-> TracerPool recycles the beam parts the projectiles leave behind
The classes are plain Luau metatable classes (Spring, TracerPool, Projectile, Target,
Turret). Each one owns its own state and exposes a small step/act interface, which is
what keeps the main loop three lines long.
]]
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
-- ============================================================================
-- 1. CONFIGURATION
-- Every tunable number sits in one frozen table. Frozen because a stray write to a
-- shared config is the kind of bug that only shows up an hour into a play session.
-- ============================================================================
local CONFIG = table.freeze({
-- Simulation. Physics runs on a fixed step so behaviour does not change with framerate:
-- a 30 fps server and a 60 fps server integrate the exact same trajectory.
StepTime = 1 / 60,
MaxStepsPerFrame = 4, -- ceiling on catch-up steps, so a lag spike cannot spiral
-- Ballistics. Drag is quadratic (proportional to speed squared), which is what makes
-- a fast round lose speed quickly and then settle into a lazy arc near the end.
MuzzleVelocity = 220,
Gravity = 96,
DragCoefficient = 0.0022,
ProjectileLifetime = 6,
LeadIterations = 3, -- fixed-point passes for the intercept solve, see solveIntercept
-- Turrets.
TurretCount = 3,
TurretSpacing = 18,
FireInterval = 0.85,
AimTolerance = 0.995, -- dot product the aim must reach before the turret is allowed to fire
SpringStiffness = 180,
SpringDamping = 26,
-- Targets.
TargetCount = 5,
TargetSpacing = 14,
TargetRange = 190,
TargetHealth = 3,
TargetRespawnDelay = 2.5,
BobAmplitude = 11,
BobFrequency = 0.9,
-- Presentation.
TracerWidth = 0.16,
TracerFadeTime = 0.12,
TracerPoolSize = 96,
WindSpeed = 38, -- horizontal wind, toggled from the control pad
})
-- Colours kept apart from the numbers above; they are read once at build time.
local PALETTE = table.freeze({
Steel = Color3.fromRGB(70, 78, 88),
Tracer = Color3.fromRGB(255, 196, 94),
TargetLive = Color3.fromRGB(96, 190, 120),
TargetDead = Color3.fromRGB(60, 64, 70),
Pad = Color3.fromRGB(200, 92, 78),
})
-- ============================================================================
-- 2. WORLD CONTAINERS AND RAYCAST FILTER
-- ============================================================================
-- One folder for things shots must ignore (turret bodies, tracers, player characters) and
-- one for things shots must hit (targets). Sorting instances by role at creation time means
-- the raycast filter is a single folder list instead of a per-cast rebuild.
local rangeFolder = Instance.new("Folder")
rangeFolder.Name = "BallisticRange"
rangeFolder.Parent = Workspace
local ignoreFolder = Instance.new("Folder")
ignoreFolder.Name = "Ignore"
ignoreFolder.Parent = rangeFolder
local targetFolder = Instance.new("Folder")
targetFolder.Name = "Targets"
targetFolder.Parent = rangeFolder
-- A single RaycastParams object, reused by every cast. Allocating one per shot is the
-- classic hidden cost in a gun system: it is cheap once and expensive sixty times a second.
local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Exclude
rayParams.IgnoreWater = true
rayParams.FilterDescendantsInstances = { ignoreFolder }
-- Character models are added to the ignore list as players spawn, so a player standing in
-- the lane watches the rounds pass through instead of soaking them.
local function watchCharacters(player: Player)
local function ignoreCharacter(character: Model)
local filter = rayParams.FilterDescendantsInstances
table.insert(filter, character)
rayParams.FilterDescendantsInstances = filter -- the property only updates on assignment
end
player.CharacterAdded:Connect(ignoreCharacter)
if player.Character then
ignoreCharacter(player.Character)
end
end
Players.PlayerAdded:Connect(watchCharacters)
for _, player in Players:GetPlayers() do
watchCharacters(player)
end
-- ============================================================================
-- 3. MATH HELPERS
-- ============================================================================
-- Builds the CFrame for a beam between two points: centred on the midpoint, pointing at
-- the far end. lookAt gives the orientation, so the part only needs a length on its Z axis.
local function beamCFrame(from: Vector3, to: Vector3): CFrame
return CFrame.lookAt((from + to) * 0.5, to)
end
-- Where should the turret aim to hit a moving target with a round that also falls?
--
-- Flight time depends on distance, and distance depends on where the target will be at
-- that flight time, so the two feed each other. Rather than solving the quartic that comes
-- out of doing it exactly, this iterates the estimate: guess a time, move the target by it,
-- measure again. Three passes land within a few centimetres at these ranges and cost three
-- square roots, which is far cheaper than the closed form and much easier to read.
--
-- Gravity is then compensated separately by raising the aim point by the drop the round
-- accumulates over that flight time (1/2 * g * t^2). Drag makes the real flight slightly
-- longer than this estimate, which is deliberate: the turrets are meant to be very good,
-- not perfect, and the residual error is what keeps the accuracy readout interesting.
local function solveIntercept(origin: Vector3, targetPos: Vector3, targetVelocity: Vector3): (Vector3, number)
local flightTime = (targetPos - origin).Magnitude / CONFIG.MuzzleVelocity
for _ = 1, CONFIG.LeadIterations do
local predicted = targetPos + targetVelocity * flightTime
flightTime = (predicted - origin).Magnitude / CONFIG.MuzzleVelocity
end
local aimPoint = targetPos + targetVelocity * flightTime
local drop = 0.5 * CONFIG.Gravity * flightTime * flightTime
return aimPoint + Vector3.new(0, drop, 0), flightTime
end
-- ============================================================================
-- 4. SPRING
-- A damped spring driving a Vector3. The turrets use it on their aim direction rather than
-- on angles: springing a direction cannot wind up past a pole or take the long way round a
-- 360 degree wrap, and the result normalises straight into CFrame.lookAt.
-- ============================================================================
local Spring = {}
Spring.__index = Spring
type SpringFields = {
position: Vector3,
velocity: Vector3,
goal: Vector3,
}
export type Spring = typeof(setmetatable({} :: SpringFields, Spring))
local function newSpring(start: Vector3): Spring
return setmetatable({
position = start,
velocity = Vector3.zero,
goal = start,
}, Spring)
end
-- Semi-implicit Euler: velocity is updated first and the new velocity moves the position.
-- It costs the same as plain Euler but does not quietly gain energy over long runs, which
-- for a spring that lives for the whole session is the difference between settling and
-- oscillating wider every minute.
function Spring.step(self: Spring, dt: number)
local offset = self.goal - self.position
local acceleration = offset * CONFIG.SpringStiffness - self.velocity * CONFIG.SpringDamping
self.velocity += acceleration * dt
self.position += self.velocity * dt
end
-- ============================================================================
-- 5. TRACER POOL
-- Tracers are the highest-churn object in the range: a few hundred parts a minute, each
-- alive for a tenth of a second. Creating and destroying them is what turns a smooth range
-- into a stuttering one, so a fixed set of parts is created once and handed out on request.
-- ============================================================================
local TracerPool = {}
TracerPool.__index = TracerPool
type TracerPoolFields = {
free: { BasePart },
active: { { part: BasePart, age: number } },
}
export type TracerPool = typeof(setmetatable({} :: TracerPoolFields, TracerPool))
local function newTracerPool(size: number): TracerPool
local free = table.create(size)
for _ = 1, size do
local part = Instance.new("Part")
part.Anchored = true
part.CanCollide = false
part.CanQuery = false -- a tracer must never block another projectile's raycast
part.CanTouch = false
part.CastShadow = false
part.Material = Enum.Material.Neon
part.Color = PALETTE.Tracer
part.Transparency = 1
part.Size = Vector3.new(CONFIG.TracerWidth, CONFIG.TracerWidth, 1)
part.Parent = ignoreFolder
table.insert(free, part)
end
return setmetatable({
free = free,
active = {},
}, TracerPool)
end
-- Draws one segment. If the pool is empty the request is dropped rather than growing the
-- pool: a missing tracer for one frame is invisible, an unbounded part count is not.
function TracerPool.draw(self: TracerPool, from: Vector3, to: Vector3)
local part = table.remove(self.free)
if not part then
return
end
local length = (to - from).Magnitude
part.Size = Vector3.new(CONFIG.TracerWidth, CONFIG.TracerWidth, length)
part.CFrame = beamCFrame(from, to)
part.Transparency = 0
table.insert(self.active, { part = part, age = 0 })
end
-- Fades the live tracers and returns the expired ones. The loop walks backwards so that
-- removing an entry cannot make it skip the next one.
function TracerPool.step(self: TracerPool, dt: number)
for index = #self.active, 1, -1 do
local entry = self.active[index]
entry.age += dt
local alpha = entry.age / CONFIG.TracerFadeTime
if alpha >= 1 then
entry.part.Transparency = 1
table.insert(self.free, entry.part)
table.remove(self.active, index)
else
entry.part.Transparency = alpha
end
end
end
-- ============================================================================
-- 6. PROJECTILE
-- A round is state, not a part: position, velocity and a way to report what it hit. The
-- visible tracer is a side effect of it moving. That split is what lets the physics run at
-- a fixed step while the visuals stay cheap.
-- ============================================================================
local Projectile = {}
Projectile.__index = Projectile
type ProjectileFields = {
position: Vector3,
velocity: Vector3,
age: number,
-- A callback rather than a reference to the turret that fired it. The round has no
-- reason to know what a turret is, and keeping the dependency one-directional means
-- neither type has to be declared before the other.
report: (landed: boolean) -> (),
}
export type Projectile = typeof(setmetatable({} :: ProjectileFields, Projectile))
-- Forward declarations. Wind is toggled from the control pad far below, the tracer pool and
-- the hit lookup are built during range assembly. Declaring the locals here keeps the file
-- in reading order - small pieces first - without Luau treating them as globals.
local wind = Vector3.zero
local tracerPool: TracerPool
local resolveHit: (instance: BasePart) -> boolean
local function newProjectile(origin: Vector3, direction: Vector3, report: (boolean) -> ()): Projectile
return setmetatable({
position = origin,
velocity = direction.Unit * CONFIG.MuzzleVelocity,
age = 0,
report = report,
}, Projectile)
end
-- Advances one fixed step and returns false when the round is finished, either because it
-- hit something or because it timed out.
--
-- The raycast goes from the previous position to the new one instead of "forward a bit"
-- from the current position. At 220 studs a second a round covers almost four studs per
-- step, so a target thinner than that would sit in the gap between two samples and never be
-- touched. Casting the segment the round actually travelled makes tunnelling impossible.
function Projectile.step(self: Projectile, dt: number): boolean
self.age += dt
if self.age > CONFIG.ProjectileLifetime then
return false
end
local speed = self.velocity.Magnitude
-- Quadratic drag: the force scales with speed squared and opposes the direction of
-- travel. Multiplying the velocity vector by its own magnitude gives both at once.
local drag = -self.velocity * (speed * CONFIG.DragCoefficient)
local acceleration = drag + wind + Vector3.new(0, -CONFIG.Gravity, 0)
self.velocity += acceleration * dt
local nextPosition = self.position + self.velocity * dt
local result = Workspace:Raycast(self.position, nextPosition - self.position, rayParams)
if result then
tracerPool:draw(self.position, result.Position)
self.report(resolveHit(result.Instance))
return false
end
tracerPool:draw(self.position, nextPosition)
self.position = nextPosition
return true
end
-- ============================================================================
-- 7. TARGET
-- Each target slides along its own sine path. The path is evaluated from absolute time
-- rather than accumulated per frame, so a target can never drift out of phase with the
-- others, and its velocity is available in closed form.
-- ============================================================================
local Target = {}
Target.__index = Target
type TargetFields = {
part: BasePart,
origin: Vector3,
phase: number,
health: number,
respawnTimer: number,
alive: boolean,
}
export type Target = typeof(setmetatable({} :: TargetFields, Target))
local function newTarget(origin: Vector3, phase: number): Target
local part = Instance.new("Part")
part.Name = "Target"
part.Anchored = true
part.CanCollide = false
part.Material = Enum.Material.SmoothPlastic
part.Color = PALETTE.TargetLive
part.Size = Vector3.new(4, 6, 1)
part.CFrame = CFrame.new(origin)
part.Parent = targetFolder
return setmetatable({
part = part,
origin = origin,
phase = phase,
health = CONFIG.TargetHealth,
respawnTimer = 0,
alive = true,
}, Target)
end
-- Position and velocity of the sine path at a given time.
--
-- The velocity is the analytic derivative of the position rather than a difference between
-- two frames. It is exact, it costs one cosine, and the turret's lead solve is only as good
-- as the velocity it is handed - a differenced velocity would lag the target by a step and
-- the turrets would consistently shoot just behind it.
function Target.sample(self: Target, clock: number): (Vector3, Vector3)
local omega = CONFIG.BobFrequency * math.pi * 2
local angle = omega * clock + self.phase
local offset = Vector3.new(math.sin(angle) * CONFIG.BobAmplitude, 0, 0)
local velocity = Vector3.new(math.cos(angle) * CONFIG.BobAmplitude * omega, 0, 0)
return self.origin + offset, velocity
end
function Target.step(self: Target, dt: number, clock: number)
if not self.alive then
self.respawnTimer -= dt
if self.respawnTimer <= 0 then
self.alive = true
self.health = CONFIG.TargetHealth
self.part.Color = PALETTE.TargetLive
self.part.CanQuery = true
end
return
end
local position = self:sample(clock)
self.part.CFrame = CFrame.new(position)
end
-- Applies one hit. Downed targets keep their part in the world but stop answering raycasts
-- via CanQuery, which removes them from the turrets' consideration without any bookkeeping
-- on the turret side.
function Target.damage(self: Target)
self.health -= 1
if self.health > 0 then
return
end
self.alive = false
self.respawnTimer = CONFIG.TargetRespawnDelay
self.part.Color = PALETTE.TargetDead
self.part.CanQuery = false
end
-- ============================================================================
-- 8. TURRET
-- ============================================================================
local Turret = {}
Turret.__index = Turret
type TurretFields = {
pivot: Vector3,
barrel: BasePart,
aim: Spring,
cooldown: number,
shots: number,
hits: number,
report: (landed: boolean) -> (),
}
export type Turret = typeof(setmetatable({} :: TurretFields, Turret))
local function newTurret(pivot: Vector3): Turret
local base = Instance.new("Part")
base.Name = "TurretBase"
base.Anchored = true
base.Shape = Enum.PartType.Cylinder
base.Material = Enum.Material.Metal
base.Color = PALETTE.Steel
base.Size = Vector3.new(1.5, 3, 3)
-- A cylinder's flat faces sit on its X axis, so it has to be rolled 90 degrees to stand
-- upright. Composing the rotation onto the position keeps that in one expression.
base.CFrame = CFrame.new(pivot - Vector3.new(0, 1.2, 0)) * CFrame.Angles(0, 0, math.rad(90))
base.Parent = ignoreFolder
local barrel = Instance.new("Part")
barrel.Name = "TurretBarrel"
barrel.Anchored = true
barrel.CanCollide = false
barrel.Material = Enum.Material.Metal
barrel.Color = PALETTE.Steel
barrel.Size = Vector3.new(0.5, 0.5, 5)
barrel.CFrame = CFrame.new(pivot)
barrel.Parent = ignoreFolder
-- The scoring callback is built once per turret and handed to every round it fires, so a
-- hit costs no allocation. Declaring the local first lets the closure capture the turret
-- it belongs to before the table itself is finished.
local turret: Turret
local function report(landed: boolean)
if landed then
turret.hits += 1
end
end
turret = setmetatable({
pivot = pivot,
barrel = barrel,
aim = newSpring(Vector3.new(0, 0, -1)),
cooldown = 0,
shots = 0,
hits = 0,
report = report,
}, Turret)
return turret
end
-- The muzzle is the barrel's local -Z end. Reading it off the barrel's own CFrame means the
-- rounds always leave from wherever the model currently points, with no second copy of the
-- aim maths to keep in sync.
function Turret.muzzle(self: Turret): Vector3
return self.barrel.CFrame * Vector3.new(0, 0, -self.barrel.Size.Z * 0.5)
end
-- One turret update: pick a target, spring the aim towards the intercept solution, point
-- the barrel, and fire when both the cooldown and the aim agree.
function Turret.step(self: Turret, dt: number, clock: number, target: Target?): Projectile?
self.cooldown -= dt
if target then
local position, velocity = target:sample(clock)
local aimPoint = solveIntercept(self.pivot, position, velocity)
self.aim.goal = (aimPoint - self.pivot).Unit
end
self.aim:step(dt)
local direction = self.aim.position
if direction.Magnitude < 1e-4 then
return nil -- degenerate spring state, skip this frame rather than normalising a zero vector
end
direction = direction.Unit
self.barrel.CFrame = CFrame.lookAt(self.pivot, self.pivot + direction)
-- Firing while the barrel is still swinging would send rounds off to the side, so the
-- turret waits until the barrel and the solution point the same way. The dot product of
-- two unit vectors is the cosine of the angle between them: 0.995 is about six degrees.
if not target or self.cooldown > 0 or direction:Dot(self.aim.goal) < CONFIG.AimTolerance then
return nil
end
self.cooldown = CONFIG.FireInterval
self.shots += 1
return newProjectile(self:muzzle(), direction, self.report)
end
-- ============================================================================
-- 9. RANGE ASSEMBLY
-- ============================================================================
tracerPool = newTracerPool(CONFIG.TracerPoolSize)
local targets: { Target } = table.create(CONFIG.TargetCount)
local turrets: { Turret } = table.create(CONFIG.TurretCount)
local projectiles: { Projectile } = {}
-- Targets are spread across the far end of the lane and each is given a different phase, so
-- they never line up into a single wall of movement.
for index = 1, CONFIG.TargetCount do
local lateral = (index - (CONFIG.TargetCount + 1) * 0.5) * CONFIG.TargetSpacing
local origin = Vector3.new(lateral, 8, -CONFIG.TargetRange)
table.insert(targets, newTarget(origin, index * (math.pi * 2 / CONFIG.TargetCount)))
end
for index = 1, CONFIG.TurretCount do
local lateral = (index - (CONFIG.TurretCount + 1) * 0.5) * CONFIG.TurretSpacing
table.insert(turrets, newTurret(Vector3.new(lateral, 6, 0)))
end
-- Targets are handed out round-robin rather than "closest first", which would leave the
-- outer turrets idle and stack every round onto one target.
local function pickTarget(turretIndex: number): Target?
local count = #targets
for offset = 0, count - 1 do
local target = targets[(turretIndex + offset - 1) % count + 1]
if target.alive then
return target
end
end
return nil
end
-- Maps a hit part back to its Target. The lookup is a table keyed by part, so a hit costs
-- one index rather than a scan over every target.
local targetByPart: { [BasePart]: Target } = {}
for _, target in targets do
targetByPart[target.part] = target
end
resolveHit = function(instance: BasePart): boolean
local target = targetByPart[instance]
if not target or not target.alive then
return false
end
target:damage()
return true
end
-- ============================================================================
-- 10. CONTROL PAD AND READOUT
-- A ClickDetector keeps the whole demo interactive without a second script: click handling
-- is delivered straight to the server, so there is no LocalScript and no remote to secure.
-- ============================================================================
local pad = Instance.new("Part")
pad.Name = "WindPad"
pad.Anchored = true
pad.Material = Enum.Material.SmoothPlastic
pad.Color = PALETTE.Pad
pad.Size = Vector3.new(8, 1, 8)
pad.CFrame = CFrame.new(0, 0.5, 16)
pad.Parent = ignoreFolder
local board = Instance.new("Part")
board.Name = "Readout"
board.Anchored = true
board.CanCollide = false
board.Transparency = 1
board.Size = Vector3.new(16, 6, 0.5)
board.CFrame = CFrame.new(0, 14, 22) * CFrame.Angles(0, math.pi, 0)
board.Parent = ignoreFolder
local surface = Instance.new("SurfaceGui")
surface.Face = Enum.NormalId.Front
surface.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud
surface.PixelsPerStud = 48
surface.Parent = board
local label = Instance.new("TextLabel")
label.Size = UDim2.fromScale(1, 1)
label.BackgroundTransparency = 1
label.Font = Enum.Font.Code
label.TextScaled = true
label.TextColor3 = PALETTE.Tracer
label.Text = ""
label.Parent = surface
local clicker = Instance.new("ClickDetector")
clicker.MaxActivationDistance = 32
clicker.Parent = pad
-- Wind is applied to the rounds but deliberately not fed into the intercept solve, so
-- switching it on is a visible demonstration of what an uncompensated crosswind does to a
-- turret that is otherwise near perfect. The readout carries the proof.
clicker.MouseClick:Connect(function()
wind = if wind == Vector3.zero then Vector3.new(CONFIG.WindSpeed, 0, 0) else Vector3.zero
pad.Color = if wind == Vector3.zero then PALETTE.Pad else PALETTE.Tracer
end)
-- The readout is rebuilt only when a number it displays has changed. Writing to a TextLabel
-- every frame replicates a property change to every client sixty times a second for text
-- that is identical most of those frames.
local lastShots, lastHits = -1, -1
local function refreshReadout()
local shots, hits = 0, 0
for _, turret in turrets do
shots += turret.shots
hits += turret.hits
end
if shots == lastShots and hits == lastHits then
return
end
lastShots, lastHits = shots, hits
local accuracy = if shots > 0 then hits / shots * 100 else 0
label.Text = string.format(
"BALLISTIC RANGE\nshots %d hits %d accuracy %.1f%%\nwind %s rounds in flight %d",
shots,
hits,
accuracy,
if wind == Vector3.zero then "calm" else "crosswind",
#projectiles
)
end
-- ============================================================================
-- 11. MAIN LOOP
-- Heartbeat delivers a variable delta; the accumulator turns it into whole fixed steps and
-- carries the remainder into the next frame. One connection drives the entire range.
-- ============================================================================
local accumulator = 0
local clock = 0
local function stepRange(dt: number)
clock += dt
for index, turret in turrets do
local fired = turret:step(dt, clock, pickTarget(index))
if fired then
table.insert(projectiles, fired)
end
end
for _, target in targets do
target:step(dt, clock)
end
-- Backwards again, and the removal is a swap with the last element instead of a shift:
-- rounds retire out of order anyway, so paying to preserve their order would be waste.
for index = #projectiles, 1, -1 do
if not projectiles[index]:step(dt) then
projectiles[index] = projectiles[#projectiles]
projectiles[#projectiles] = nil
end
end
tracerPool:step(dt)
end
RunService.Heartbeat:Connect(function(deltaTime: number)
accumulator += deltaTime
local steps = math.min(math.floor(accumulator / CONFIG.StepTime), CONFIG.MaxStepsPerFrame)
accumulator -= steps * CONFIG.StepTime
for _ = 1, steps do
stepRange(CONFIG.StepTime)
end
refreshReadout()
end)
- Projectiles with quadratic drag, gravity and wind on a fixed timestep
- CFrame math for barrels, beams and turret orientation
- Metatable classes for springs, tracer pools, projectiles, targets and turrets
Music & sound
Chase themes for my game projects. Pick a theme; nothing plays until you press play.
Theme 1
0:00 / 1:26Clothing
Classic clothing I design for Roblox avatars.
- Piece
- Striped knit shirt with jeans
- Type
- Classic shirt and pants
- Shown on
- A blank avatar
Started at 13. Still building.
I grew up making things in Roblox and I still spend most of my free time on it. A lot of what I build stays a private prototype; this page holds the parts I can show.
Right now I’m working toward a German university of applied sciences entrance qualification (Fachhochschulreife).
Shown on this page
- Luau systems and a physics demo
- Clothing designs
- Chase themes for my games
From experience
- Private game prototypes
- Game feel and what keeps players coming back
Still learning
- QA and optimization
- AI-assisted workflows
- Game investment (no professional experience)