我已经坐在笔记本电脑上大约一个小时,试图弄清楚发生了什么。昨天我做了同样的事情,它奏效了。请帮助。
说明程序:该程序将获取鼠标所指向的对象,如果单击该对象将趋向于鼠标。
local player = game.Players.LocalPlayer
local runservice = game:GetService("RunService")
local character = player.Character
local humanoid = character.Humanoid
local camera = workspace.Camera
local mouse = player:GetMouse()
local mousepos = mouse.hit.p
local grabbed = false
local function grabbedobj(obj) --this is the thing i need help on
local bodypos = obj.BodyPosition.Position
local pos = obj.Position
obj.Anchored = false
mouse.Button1Down:Connect(function()
grabbed = true
end)
mouse.Button1Up:Connect(function()
grabbed = false
end)
if grabbed == true then
print(obj.BodyPosition.Position)
bodypos = Vector3.new(mousepos.X, mousepos.Y, mousepos.Z) --really important
end
if grabbed == false then
bodypos = Vector3.new(pos.X, -25, pos.Z)
pos = Vector3.new(bodypos.X, pos.Y, bodypos.Z)
end
end
local function setup()
mousepos = mouse.hit.p
if mouse.Target ~= nil and mouse.Target.Parent == game.Workspace.IntObj then
grabbedobj(mouse.Target) --takes object that the mouse is pointing at
end
end
while wait(.1) do
setup()
end
让代码稍微整理一下,以便它执行我认为您想做的事情。在尝试调试时,您可能混淆了一些东西。所以这里:
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local grabbed = false
local obj
mouse.Button1Down:Connect(function()
if mouse.Target ~= nil and mouse.Target.Parent == game.Workspace.IntObj then
obj = mouse.Target
obj.Anchored = false
grabbed = true
end
end)
mouse.Button1Up:Connect(function()
if (grabbed) then
grabbed = false--BodyPosition
obj.BodyPosition.Position = Vector3.new(obj.Position.X, 0.1, obj.Position.Z)
obj.Anchored = true
end
end)
local function move()
if (grabbed) then
local mousepos = mouse.hit.p
obj.BodyPosition.Position = Vector3.new(mousepos.X, mousepos.Y, mousepos.Z)
print(obj.BodyPosition.Position)
end
end
while wait(.1) do
move()
end
当您单击鼠标时,它会检查您是否单击了IntObj中的零件。它将保留对该零件的引用,然后用鼠标移动它。释放按钮时,它将放置在其位置。
因此,此LocalScript应该可以工作,但是如您在标题中所述,更新BodyPosition时遇到问题。这样做的原因是,如果您从服务器授予客户端许可,则只能从客户端更新服务器部件。您可以在服务器上编写远程功能,然后说:
game.ReplicatedStorage.RemoteFunction.OnServerInvoke = function(plr)
Workspace.IntObj.Part:SetNetworkOwner(plr)
end
如果您从本地脚本的初始化中调用它,它将起作用。请注意,您的零件无法为此固定。
另一种方法是只让服务器进行更新。因此,与其设置在客户端上的obj.BodyPosition.Position,您将像这样调用远程函数:
game.ReplicatedStorage.RemoteFunction:InvokeServer(Vector3.new(mousepos.X, mousepos.Y, mousepos.Z))
然后在服务器上设置位置:
game.ReplicatedStorage.RemoteFunction.OnServerInvoke = function(plr, bodyPos)
script.Parent.BodyPosition.Position = bodyPos
end
在这种情况下,如果您锚固/锚固零件,那么也要在服务器上执行该操作。否则,您将得到奇怪的结果。