我正在尝试学习 ROBLOX lua 脚本编写,但有一个问题,我忘记如何正确使用触摸事件了

以下是我遇到的问题。

local part = game.Workspace.Part

part.Anchored = true
part.Touched:Connect(function(hit)
    if hit.Parent:GetPlayerFromCharacter(hit.Parent) then
        wait(0.7)
        hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 2
    end
end)

你看到的是 ROBLOX Studio 中的一些非常简单的脚本。 此脚本类型为常规脚本。 我需要的帮助是它无法从玩家身上减少生命值。

点赞
用户15107943
用户15107943

要使用函数 GetPlayerFromCharacter(hit.Parent),你需要使用 Players 服务。我已经为你修复代码:

local part = game.Workspace.Part
-- 获取 Players 服务
local PlayersService = game:GetService('Players')

part.Anchored = true
part.Touched:Connect(function(hit)
    -- 使用 Players 服务使函数正常工作
    if PlayersService:GetPlayerFromCharacter(hit.Parent) then
        wait(0.7)
        hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 2
    end
end)
2021-04-21 13:01:36
用户2858170
用户2858170

从 Roblox 手册中:

https://developer.roblox.com/en-us/articles/detecting-collisions

local part = script.Parent

local function onPartTouched(otherPart)
  -- 获取其他物体的父级部件
  local partParent = otherPart.Parent
  -- 在父级部件中查找玩家
  local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")
  if humanoid then
      -- 对玩家执行一些操作,比如将其生命值设为0
      humanoid.Health = 0
  end
end

part.Touched:Connect(onPartTouched)

我忘记了如何正确使用触碰事件

这就是为什么人们编写手册的原因。这样你不必记住所有的东西。

2021-04-21 13:02:40