I am learning Lua and Roblox and testing my first scripts. I would like to know the right method to manage the touch event when the character touch a block with his feet, (whether walking or jumping)
local function onTouch(hit)
if hit ~= ??user.legs?? then
return
end
-- exemple of action
if hit.Parent.Humanoid.JumpPower < 150 then
hit.Parent.Humanoid.JumpPower = hit.Parent.Humanoid.JumpPower + 5;
end
end
script.Parent.Touched:connect(onTouch)
If you're trying to handle the collision when a player touches a part with his legs, your code is fine, but if you want to detect when a player is standing in the ground or not, then, it isn't.
A better approach would be the following:
Example:
IsOnGround=function()
local b=false;
local range=6;
local char=game:service("Players").LocalPlayer.Character;
local root=char:WaitForChild("HumanoidRootPart",1);
if root then
local ray=Ray.new(root.CFrame.p,((root.CFrame*CFrame.new(0,-range,0)).p).unit*range);
local ignore={char};
local hit,pos=workspace:FindPartOnRayWithIgnoreList(ray,ignore,false,false);
pcall(function()
if hit then
b=true;
end
end)
else
print("root not found");
end
return b;
end
Though, this method isn't the most reliable, it doens't like R15 characters, nor walking.
A method that will work like 99% of the times, and is easy to use, is FloorMaterial.
FloorMaterial is a property of the Character's Humanoid. This property will be nil if the player isn't standing on anything (in other words, not touching the ground!) This method can be put in a loop to constantly detect whether if you're standing on a block or not. This method, also, works for both R15 and R6, and is less glitchy than using a .Touched connection.
Example:
coroutine.wrap(function()
while wait()do
local floor=humanoid.FloorMaterial
if(tostring(floor)=="Enum.Material.Air")or(floor==nil)then
print("on air");
else
print("stepping over something");
end
end
end)()
Hope my answer helps.