块上的 Roblox 触摸事件仅适用于脚

Roblox touch event on a block only for feets

我正在学习 Lua 和 Roblox 并测试我的第一个脚本。 我想知道当角色用脚触摸方块(无论是行走还是跳跃)[时,管理触摸事件的正确方法=11=]

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)

如果你试图处理玩家用腿接触某个部分时的碰撞,你的代码是好的,但如果你想检测玩家何时站在地上,那么,它是't.

更好的方法如下:

示例:

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

虽然这个方法不是最靠谱的,它不喜欢R15字,也不喜欢走路

FloorMaterial 是一种在 99% 的情况下都有效且易于使用的方法。

FloorMaterial 是 Character 的 Humanoid 的 属性。如果玩家没有站在任何东西上(换句话说,没有接触地面!),这个 属性 将为 nil不是。此方法也适用于 R15 和 R6,并且比使用 .Touched 连接时故障更少。

示例:

    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)()

希望我的回答对您有所帮助。