Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

A script to detect movement?

I wanted a script to detect movement for like a security alarm, I wanted to like put the script in a case and when it detects a person within 4 metres it sets the alarm off, Could someone provide an example script for this?

Thanks,

EliteGamingChicken

3 answers

✓ Accepted answer

Best way to do this would be a magnitude check from the camera to the players torso, magnitude is fortunately a property of any vector calculation so your script could look something like this

local camera = script.Parent

while true do
	wait()
	for k, v in next, game.Players:GetChildren() do
		local torso = v.Character.Torso
		if (camera.Position - torso.Position).magnitude < 20 then -- assuming 5 studs is a meter.
			soundAlarm(); -- a function you can define for the alarm stuff
		end
	end
end

Hope this helps.

I think you should use FindPartOnRay() for that, but OnTouched() will be fine too.

Main = script.Parent

function onTouched(part)
	--do something over there
end
 
Main.Touched:connect(onTouched)

Edit

local ray = Ray.new(
		Vector3.new(0, 0, 0), -- Where to start
		Vector3.new(4, 0, 0) -- How long
		)
local part = game.Workspace:FindPartOnRay(ray)
	if part.Name == "Torso" or "LeftLeg" or "RightLeg" or "Head" or "LeftArm" or "RightArm" then
	--Do alarm thing there
end

1 comment

0

The only problem with that, Panzer is i dont want the thing to be touched I want the find part on ray bit could you change the script to findpartonray() for me please, Thanks

Here, I wrote a simple script for you to use to do that. Modify the variable, dist, to the amount of studs the player must be within to set off the alarm. Also, make sure you point the alarm variable to the alarm.

alarm = -- point to the alarm

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local temp = nil
	local dist = 10
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("Torso")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end

while wait() do
	target = findNearestTorso(alarm.Position)
	if(target ~= nil) then
		-- start alarm
	else
		-- stop alarm
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.