Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to move object when its clicked ?

Hi, I have a question about moving objects. i try to move a part when i cklick on it. The script I made looks like this:

local ClickDetector = script.Parent.ClickDetector
 
ClickDetector.MouseClick:Connect(function move(x,y,z)
		for i=1,10 do
			script.Parent.Position = script.Parent.Position + Vector3.new(x,y,z)
			wait(0.01)
		end
	end

	while true do
		move(1,0,0)
		move(-1,0,0)
	end
end

Please can you tell me why it doesnt work.

1 answer

Because that's not how events work... A better and working approach is...

local ClickDetector = script.Parent.ClickDetector

function move(x, y, z)
    for i = 1, 10 do
        script.Parent.Position = script.Parent.Position + Vector3.new(x, y, z)
        wait(0.01)
    end

    while true do
        move(1, 0, 0)
        move(-1, 0, 0)
    end
end

ClickDetector.MouseClick:Connect(function()
    while true do
       move(1, 0, 0)
       move(-1, 0, 0)
    end
    
    wait(0.1)
end)

2 comments

1

The best functional approach, is using TweenService.

0

On line 9, your script might timeout, you'll need a wait somewhere in that loop. That might mean making it a while wait() do loop

This discussion is preserved as it was. New answers, comments, and votes are closed.