So I thought of having this for so long, I just don't know where to start. I am new to this language and I keep learning, but kind of hard for me. But I have built my very own custom character which took 2 weeks for me. Anyway, For my question. An example is if I have a button and I click it, a model will be clone and I can drag that model and put it anywhere nearby. What possible method I can use to achieve this?
First things first, I suggest for any future questions, you head over to https://scriptinghelpers.org/
now, on to your question, for cloning the model, you should use mouse.Target.Parent:Clone() or the GetTopParent(mouse.Target) function in my function library (which you can get here; http://www.roblox.com/item.aspx?id=244244638)
then deposit the model into workspace and MakeJoints()
the next step is to move the model, this can be tricky, but the simplest method is model:MoveTo(mouse.Hit.p) on mouse.Moved (but that's a little buggy)
Another method for movement would be to use the Handles class, but I'm not really familiar with it, so you'd have to figure that one out on your own.
To make the first method less buggy, I'd suggest something along the lines of
model:MoveTo(mouse.Hit.p.X, mouse.Target.Position.Y + (model:GetExtentsSize().Y / 2), mouse.Hit.p.Z)
but you'd have to set up the mouse to ignore the model, which I can't really help with.
A really good place to start is to search the free models in Studio Toolbox for a 'Dragger Tool' or 'Model Dragger Tool' and then use the script inside to get started creating your own. I have learned to create my own custom draggers by doing this and it is way easier than you may think at first. Once you find a good dragger tool to borrow code from, if you need to enhance it, you can find the dragger api in the Roblox Wiki to help you further customize it to your specific needs.
http://wiki.roblox.com/index.php?title=API:Class/Dragger
EDIT: So here's the first dragger script that showed when I searched. It will drag models and parts but you will have to edit it to meet your requirements using the dragger api. Create a Tool in player.BackPack then create a LocalScript inside the Tool then copy and paste the code below into the LocalScript, and that will get you started.
local Tool = script.Parent
enabled = true
local origTexture = Tool.TextureId
game:GetService("ContentProvider"):Preload("rbxasset://icons/freemove_sel.png")
local selectionBox
local currentSelection
local currentSelectionColors = {}
local selectionLasso
local inGui = false
local inPalette = false
local lockTime = 0
function canSelectObject(part)
return part and not (part.Locked) and (part.Position - script.Parent.Parent.Head.Position).Magnitude < 60
end
function findModel(part)
while part ~= nil do
if part.className == "Model" then
return part
end
part = part.Parent
end
return nil
end
function startDrag(mousePart, hitPoint, collection)
dragger = Instance.new("Dragger")
pcall(function() dragger:MouseDown(mousePart, hitPoint, collection) end)
end
function collectBaseParts(object, collection)
if object:IsA("BasePart") then
collection[#collection+1] = object
end
for index,child in pairs(object:GetChildren()) do
collectBaseParts(child, collection)
end
end
function onMouseDown(mouse)
mouse.Icon ="rbxasset://textures\\GrabRotateCursor.png"
local part = mouse.Target
if canSelectObject(part) then
local hitPoint = mouse.Hit:toObjectSpace(part.CFrame).p
if trySelection(part) then
local instances = {}
collectBaseParts(currentSelection, instances)
startDrag(part, hitPoint, instances)
return
end
end
--Clear the selection if we weren't able to lock succesfullu
onMouseUp(mouse)
end
function onMouseUp(mouse)
mouse.Icon ="rbxasset://textures\\GrabCursor.png"
if dragger ~= nil then
pcall(function() dragger:MouseUp() end)
dragger = nil
end
end
function trySelection(part)
if canSelectObject(part) then
selectionLasso.Part = part
local model = findModel(part)
if model then
return setSelection(model)
else
return setSelection(part)
end
else
clearSelection()
return false
end
end
function onKeyDown(key)
if dragger ~= nil then
if key == 'R' or key == 'r' then
dragger:AxisRotate(Enum.Axis.Y)
elseif key == 'T' or key == 't' then
dragger:AxisRotate(Enum.Axis.Z)
end
end
end
local alreadyMoving
function onMouseMove(mouse)
if alreadyMoving then
return
end
alreadyMoving = true
if dragger ~= nil then
--Maintain the lock
if time() - lockTime > 3 then
Instance.Lock(currentSelection)
lockTime = time()
end
--Then drag
pcall(function() dragger:MouseMove(mouse.UnitRay) end)
else
trySelection(mouse.Target)
end
alreadyMoving = false
end
function saveSelectionColor(instance)
if instance:IsA("BasePart") then
currentSelectionColors[instance] = instance.BrickColor
if instance.BrickColor == BrickColor.Blue() then
instance.BrickColor = BrickColor.new("Deep blue")
else
instance.BrickColor = BrickColor.Blue()
end
end
local children = instance:GetChildren()
if children then
for pos, child in pairs(children) do
saveSelectionColor(child)
end
end
end
function setSelection(partOrModel)
if partOrModel ~= currentSelection then
clearSelection()
if Instance.Lock(partOrModel) then
lockTime = time()
currentSelection = partOrModel
saveSelectionColor(currentSelection)
selectionBox.Adornee = currentSelection
return true
end
else
if currentSelection ~= nil then
if time() - lockTime > 2 then
--Maintain the lock
if not(Instance.Lock(currentSelection)) then
--we lost the lock
clearSelection()
return false
else
lockTime = time()
return true
end
else
return true
end
end
end
return false
end
function clearSelection()
if currentSelection ~= nil then
for part, color in pairs(currentSelectionColors) do
part.BrickColor = color
end
selectionBox.Adornee = nil
Instance.Unlock(currentSelection)
end
currentSelectionColors = {}
currentSelection = nil
selectionLasso.Part = nil
selectionBox.Adornee = nil
end
function onEquippedLocal(mouse)
Tool.TextureId = "rbxasset://icons/freemove_sel.png"
local character = script.Parent.Parent
local player = game.Players:GetPlayerFromCharacter(character)
inGui = false
inPalette = false
mouse.Icon ="rbxasset://textures\\GrabCursor.png"
mouse.Button1Down:connect(function() onMouseDown(mouse) end)
mouse.Button1Up:connect(function() onMouseUp(mouse) end)
mouse.Move:connect(function() onMouseMove(mouse) end)
mouse.KeyDown:connect(function(string) onKeyDown(string) end)
selectionBox = Instance.new("SelectionBox")
selectionBox.Name = "Model Delete Selection"
selectionBox.Color = BrickColor.Blue()
selectionBox.Adornee = nil
selectionBox.Parent = player.PlayerGui
selectionLasso = Instance.new("SelectionPartLasso")
selectionLasso.Name = "Model Drag Lasso"
selectionLasso.Humanoid = character.Humanoid
selectionLasso.archivable = false
selectionLasso.Visible = true
selectionLasso.Parent = game.workspace
selectionLasso.Color = BrickColor.Blue()
alreadyMoving = false
end
function onUnequippedLocal()
Tool.TextureId = origTexture
clearSelection()
selectionBox:Remove()
selectionLasso:Remove()
end
Tool.Equipped:connect(onEquippedLocal)
Tool.Unequipped:connect(onUnequippedLocal)
Related
My goal is to create a script that warns when you are disenchanting a piece you don't want. When disenchanting an item straight from inventory, I could use the UseInventoryItem() API. Since UseInventoryItem() seems to work only on inventory slot right click, I created this script, based on GetMouseFocus() API, that works with the original interface of the game: but if someone used an addon, would it still work?
Of course, better solutions are welcome
local mt = {
__index = {
isvalue = function(t, value)
local is = false
for k, entry in ipairs(t) do
if (entry == value) then
is = true
break
end
end
return is
end
}
};
local protected = { "item1", "item2", "item3", "etch." }; -- items I want to protect
setmetatable(protected, mt);
local disenchanting;
local antidisenchant = CreateFrame("Frame");
antidisenchant:RegisterEvent("UNIT_SPELLCAST_SENT");
antidisenchant:SetScript("OnEvent", function(self, event, ...)
if (event == "UNIT_SPELLCAST_SENT") then
if (arg2 == "Disenchant") then
disenchanting = true
end
end
end);
antidisenchant:SetScript("OnUpdate", function()
if GetMouseFocus() then -- GetMouseFocus() returns the frame that currently has mouse focus.
local TargetItemID = GetInventoryItemID("player",GetMouseFocus():GetID()) -- The IDs of each inventory slot frame have the same id as the slot (16 for main hand, 17 for off hand etc.).
if (TargetItemID) and (string.find(GetMouseFocus():GetName(),"Slot")) then -- Inventory slot frame are named like "CharacterMainHandSlot".
local name, link = GetItemInfo(TargetItemID)
if (disenchanting) and (protected:isvalue(name)) then
DEFAULT_CHAT_FRAME:AddMessage("WARNING! YOU'RE DISENCHANTING "..link,1,0,0)
end
end
end
end)
I tried to fix some Garry's Mod addon and this is what happens. I tried to fix it for long time, but I'm not the best in Lua coding :/ . What is wrong with this code? I get this error:
[ERROR] addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80: bad argument #1 to 'SetPhysicsAttacker' (Entity expected, got nil)
1. SetPhysicsAttacker - [C]:-1
2. unknown - addons/garrys_bombs_5_base_528449144/lua/entities/gb5_shockwave_sound_lowsh.lua:80
And the code is pretty long. I have every file working fine, but this file is not working
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
if (SERVER) then
util.AddNetworkString( "gb5_net_sound_lowsh" )
end
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.GBOWNER = nil
ENT.MAX_RANGE = 0
ENT.SHOCKWAVE_INCREMENT = 0
ENT.DELAY = 0
ENT.SOUND = ""
net.Receive( "gb5_net_sound_lowsh", function( len, pl )
local sound = net.ReadString()
LocalPlayer():EmitSound(sound)
end );
function ENT:Initialize()
if (SERVER) then
self.FILTER = {}
self:SetModel("models/props_junk/watermelon01_chunk02c.mdl")
self:SetSolid( SOLID_NONE )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self.Bursts = 0
self.CURRENTRANGE = 0
self.GBOWNER = self:GetVar("GBOWNER")
self.SOUND = self:GetVar("SOUND")
end
end
function ENT:Think()
if (SERVER) then
if not self:IsValid() then return end
local pos = self:GetPos()
self.CURRENTRANGE = self.CURRENTRANGE+(self.SHOCKWAVE_INCREMENT*10)
if(GetConVar("gb5_realistic_sound"):GetInt() >= 1) then
for k, v in pairs(ents.FindInSphere(pos,self.CURRENTRANGE)) do
if v:IsPlayer() then
if not (table.HasValue(self.FILTER,v)) then
net.Start("gb5_net_sound_lowsh")
net.WriteString(self.SOUND)
net.Send(v)
v:SetNWString("sound", self.SOUND)
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
if GetConVar("gb5_sound_shake"):GetInt()== 1 then
util.ScreenShake( v:GetPos(), 5555, 555, self.shocktime, 500 )
end
table.insert(self.FILTER, v)
end
end
end
else
if self:GetVar("Shocktime") == nil then
self.shocktime = 1
else
self.shocktime = self:GetVar("Shocktime")
end
local ent = ents.Create("gb5_shockwave_sound_instant")
ent:SetPos( pos )
ent:Spawn()
ent:Activate()
ent:SetPhysicsAttacker(ply)
ent:SetVar("GBOWNER", self.GBOWNER)
ent:SetVar("MAX_RANGE",50000)
ent:SetVar("DELAY",0.01)
ent:SetVar("Shocktime",self.shocktime)
ent:SetVar("SOUND", self:GetVar("SOUND"))
self:Remove()
end
self.Bursts = self.Bursts + 1
if (self.CURRENTRANGE >= self.MAX_RANGE) then
self:Remove()
end
self:NextThink(CurTime() + (self.DELAY*10))
return true
end
end
function ENT:OnRemove()
if SERVER then
if self.FILTER==nil then return end
for k, v in pairs(self.FILTER) do
if not v:IsValid() then return end
v:SetNWBool("waiting", true)
end
end
end
function ENT:Draw()
return false
end
Is there a chance someone fix this for me? Or even just telling me what's wrong? I would be pleased. If needed I can send all files. Well... It's not my addon but I'm trying to fix an existing one. Someone tried to fix it too but he didn't (actually he broke it even more).
What the error means
Inside your ENT:Think() function, you are calling ent:SetPhysicsAttacker(ply)
ply is not defined anywhere inside that function, so is nil (Entity expected, got nil)
How to fix this
If no player is responsible for the damage caused by this entity, delete the line ent:SetPhysicsAttacker(ply).
Otherwise, assign an Owner to the entity at the point of creation, using SetOwner.
This would then allow you to use self:GetOwner() inside your Think hook
Example
hook.Add("PlayerSay", "SpawnEntity", function(ply, text)
if string.lower(text) == "!spawnentity" then
-- Create your entity
local myEntity = ents.Create("gb5_shockwave_sound_lowsh")
myEntity:SetPos(ply:GetPos())
myEntity:SetAngles(ply:GetAngles())
myEntity:Spawn()
-- Sets the owner to the player that typed the command
myEntity:SetOwner(ply)
return ""
end
end)
-- Inside your entity code
function ENT:Think()
print("My owner is: " .. tostring(self:GetOwner()))
-- ...
ent:SetPhysicsAttacker(self:GetOwner())
end
Last time I wanted to update my LUA code to be more automatic. Earlier had to turn on and off everything manual, by deleting phrases. But I met small problem name expected near '2' error and I'm not sure what's wrong is with it. I was looking in other thread about similar error, but they didn't help me.
local BOSS = GetModConfigData("BOSS") --return true or false
local KOAL = GetModConfigData("KOAL") --return true or false
local SCULP = GetModConfigData("SCULP") --return true or false
local BossList = {"BOSS", "KOAL", "SCULP"}
local BossCode = {"bosscode", "koal_old", "koal_new", "sculp_small", "sculp_med", "sculp_big"}
k = 1
for i,v in ipairs(BossList) do
if BossList[i] == true then
if BossList[i] == "KOAL" then
for i,2 do
Bosses[k] = BossCode[k]
k = k+1
end
elseif BossList[i] == "SCULP" then
for i,3 do
Bosses[k] = BossCode[k]
k = k+1
end
else
Bosses[k] = BossCode[k]
k = k+1
end
end
end
When I'm trying to use second loop, problem comes to me. When I pushed this code without second and third loop, it was working. But without save additional BossCodes.
for i,v in ipairs(BossList) do
if BossList[i] == true then
Bosses[k] = BossCode[k]
k = k+1
end
end
How should I make this code work? The Judoon character must regenerate, (respawn) when I click on the wall but only when he is dead.[![Regenerate][1]][1] When I click on the wall, my Judoon character has to respawn but only when he is dead.
Also how can I introduce Regen Button, the script, be separate from the Judoon model, but it should work. If you put the script Regen into Workspace, separate from the Judoon folder, it will not work.
local box = script.Parent
local debounce = false
-- DO NOT GROUP THIS WITH YOUR MODEL!
local everything = {Judoon}
local names = {Judoon}
local children = game.Workspace:children()
for i=1,#children do
if (children[i].Name == "Judoon") then -- Replace the name with your models's name.
table.insert(everything, children[i]:clone())
table.insert(names, children[i].Name)
end
end
function regen()
for i=1,#everything do
game.Workspace:findFirstChild(names[i]):remove() -- Dont mess with this stuff.
new_thing = everything[i]:clone()
new_thing.Parent = game.Workspace
new_thing:makeJoints()
end
end
function onClicked()
if Judoon:FindFirstChild("Judoon"):GetState() == Enum.HumanoidStateType.Dead then
regen()
end
end
wait(15)-- This is how long it takes untill the regen button will work again.
script.Parent.BrickColor = BrickColor.new(104)
debounce = false
end
script.Parent.ClickDetector.MouseClick:connect(onClicked)
--This regen button was made by andymewborn,hope you like(d) it!
[1]: https://i.stack.imgur.com/HhLo3.png
You can do something like this, if the humanoid is dead then regenerate.
function onClicked()
if Judoon:FindFirstChild("Judoon"):GetState() == Enum.HumanoidStateType.Dead then
regen()
end
end
New edit:
--[[
1. Put this script inside the button
2. Rename the modelname
3. The model must be a child of Workspace
--]]
button = script.Parent
modelname = "Pk" -- Model name
model = game.Workspace:FindFirstChild(modelname)
backup = model:Clone()
function Regen()
local Old =game.Workspace:FindFirstChild(modelname)
Old:Destroy()
local New = backup:Clone()
model = New -- new changes made here
New.Parent = workspace
New:MakeJoints()
end
function onClicked()
if button.BrickColor == BrickColor.new("Bright violet") then
if model:FindFirstChild("Humanoid") ~= nil then
if model.Humanoid:GetState() == Enum.HumanoidStateType.Dead then
Regen()
print("removed and added")
end
end
button.Regen:Play()
button.BrickColor = BrickColor.new("Really black")
wait(3)
button.BrickColor = BrickColor.new("Bright violet")
end
end
button.ClickDetector.MouseClick:Connect(onClicked)
I'm trying to write a lua script to assist in modifying a game, and it keeps breaking on one particular line of one of my assistant libraries.
odfWriter.lua:
require 'loopsetup'
require 'ioWriter'
local open = {}
odfWriter = class{
writer = false
}
odfWriter[open] = false
function odfWriter:open(name)
if not self[open] then
self.writer = ioWriter()
self.writer:open(name)
self[open] = true
else
error("tried to open an already open writer")
end
end
function odfWriter:write(args)
self.writer:write(args.Key .. " = ") --<-- error is here, when trying to access args
if args.Type == "seqstrings" then
for k,v in pairs(args.Value) do
self.writer:write("\"" .. v .. "\" ")
end
elseif args.Type == "string" then
self.writer:write("\"" .. args.Value .. "\"")
elseif args.Type == "seqnumbers" then
for k,v in pairs(args.Value) do
self.writer:write(tostring(v) .. " ")
end
elseif args.Type == "number" then
self.writer:write(tostring(args.Value))
elseif args.Type == "boolean" then
if args.Value == true then
self.writer:write("1")
elseif args.Value == false then
self.writer:write("0")
end
end
self.writer:write("\n")
end
function odfWriter:close()
if self[open] then
self.writer:close()
self.writer = false
self[open] = false
else
error("tried to close an already closed writer")
end
end
loopSetup.lua
-----------------------------------------------------------------------
-- file : loopsetup.lua
-- description : provides global access to all of the (known) members
-- of the loop.simple code (for easier access)
-----------------------------------------------------------------------
require 'loop.simple'
class = loop.simple.class
classof = loop.simple.classof
initclass = loop.simple.initclass
instanceof = loop.simple.instanceof
isclass = loop.simple.isclass
memberof = loop.simple.memberof
members = loop.simple.members
new = loop.simple.new
rawnew = loop.simple.rawnew
subclassof = loop.simple.subclassof
superclass = loop.simple.superclass
ioWriter.lua:
local loaded = require('loopsetup')
assert(loaded, 'loopsetup not loaded')
local open = {}
ioWriter = class{
stream = false
}
ioWriter[open] = false
function ioWriter:open(name)
if not self[open] then
self.stream = io.open(name, "w")
self[open] = true
else
error("attempted to open an already open writer")
end
end
function ioWriter:write(str)
self.stream:write(str)
end
function ioWriter:writeLine(str)
self.stream:write(str .. '\n')
end
function ioWriter:close(self)
if self[open] then
self.stream:flush()
self.stream:close()
self.stream = false
self[open] = false
else
error("attempted to close an already closed writer")
end
end
test code:
require 'loopsetup'
require 'odfWriter'
local odf = odfWriter()
odf:open('test.odf')
local line1Data = {
Type = "seqstrings",
Key = "engineTargetHardpoints",
Value = {"hp01", "hp02", "hp03"}
}
odf:write(line1data)
odf:close()
Why do i have this error when i am clearly passing in a valid table to odfwriter.write?
At least in your test code, you have a typo:
line1data ~= line1Data
You also have a typo in ioWriter.lua in the close method:
function ioWriter:close(self)
should be
function ioWriter:close()
You haven't explicitly checked that everything implementing odf:open() succeeded. My concern is that it looks like the whole flow control in of odf:open() seems to assume that everything succeeded. Is it possible that it didn't, and as a result that at the line indicated the error is caused by attempting to index self.writer containing nil?
It could be nil as opposed to false if odfWriter:open() didn't successfully execute the constructor self.writer = ioWriter() for example. I'm not a regular user of loop, so I might be barking up the wrong tree, but...
If that were happening, it would be easy to get a message that is confused about which index was at fault.
Perhaps dropping calls to assert() in a few choice spots would be productive.