We use cookies on this site to enhance your user experience

RunService Stepped

RunService Stepped

Oct 01 2018, 1:25 AM PST

This code sample uses RunService’s Stepped event to create a Part that flies in a direction given a start position and speed. It uses a BodyPosition to move the Part, and calculates the new position of the Part each frame.

local RunService = game:GetService("RunService")

local PART_START_POS = Vector3.new(0, 10, 0)
local PART_SPEED = Vector3.new(10, 0, 0)

-- Create a Part with a BodyPosition
local part = Instance.new("Part")
part.CFrame = CFrame.new(PART_START_POS)
local bp = Instance.new("BodyPosition")
bp.Parent = part
bp.Position = PART_START_POS
part.Parent = workspace

local function onStep(currentTime, deltaTime)
	-- Move the part the distance it is meant to move
	-- in the last `deltaTime` seconds
	bp.Position = bp.Position + PART_SPEED * deltaTime
	-- Here's the math behind this:
	-- speed = displacement / time
	-- displacement = speed * time