Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you script a model that moves to the side once touched?

Asked by 10 years ago

How do you make a script that makes a Model move to the side once you touch it, I have been messing up on this.

1 answer

Log in to vote
0
Answered by
Tiranin 45
10 years ago

for loops are the deity of searching world!

local Model = nil -- replace nil with the destination of Model

function Move()
    for i, v in pairs(Model:GetChildren()) do
        if v:IsA"BasePart" then
            v.CFrame = v.CFrame + Vector3.new(0,0,0) -- simply change the direction
        end
    end
end

-- this 'for loop' makes sure that function works on all parts of Model
for x, y in pairs(Model:GetChildren()) do
    if y:IsA"BasePart" then
        y.Touched:connect(Move)
    end
end

This simple code works like this:

  • it goes through all children of Model

  • if the child is BasePart, then it will move it

:GetChildren() method gets all the children of the Model and puts them into a table, meanwhile pairs function sorts those children by Key and Value and finally for loop is used to search through all of the table's content!

Note: this is a simple script and is made with hypothesis that contents of Model are only Parts and not other Models (or other children carriers).

Final Note: this script does not have debounce, meaning that once the part is touched and moved, it can be touched and moved again instantly - which can lead to some shameful situations if you keep touching the parts.

Ad

Answer this question