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

Keyboard script help?

Asked by
JJ_B 250 Moderation Voter
9 years ago

I made a keyboard-like model and I'm trying to make it so when you click a key it goes down for 0.2 seconds and then back up, like a keyboard would. The script I made doesn't work, and the output tells me " Workspace.Console.Keys.Union.Script:4: bad argument #2 to '?' (Vector3 expected, got userdata)"

pos = script.Parent.CFrame

function click()
    pos = pos + CFrame.new(0, -0.2, 0)
    wait(0.2)
    pos = pos + CFrame.new(0, 0.2, 0)
end

script.Parent.ClickDetector.MouseClick:connect(click)

Somebody please help?

0
Why delete the last question? No thanks? xPolarium 1388 — 9y
1
Have you considered that you cannot add CFrames together? LostPast 253 — 9y
0
I didn't know this. If this is true, can somebody actually post an answer? JJ_B 250 — 9y
0
@mike, This question IS the answer you gave, which doesn't work. JJ_B 250 — 9y

1 answer

Log in to vote
0
Answered by
Unclear 1776 Moderation Voter
9 years ago

First, CFrame values cannot be added to anything. You will need to use a Vector if you want to add, or do CFrame composition with the multiplicative operator (but make sure that your offset is really what you are looking for, since CFrame composition is relative to the left CFrame). Vectors are perfect for this problem because you are just looking for a simple offset irrespective of rotation, I believe.

So, rather than CFrame.new() + CFrame.new(0, 1 ,0), do CFrame.new() + Vector3.new(0, 1, 0).

Second, just because you overwrite a variable doesn't mean that what the variable was originally set to will change. You set pos to the CFrame of the parent of the script, but changing pos will not mean you are changing the CFrame. Instead, you are changing pos so nothing will really be happening.

So, rather than pos = pos + Vector3.new(0, -0.2, 0), do script.Parent.CFrame = pos + Vector3.new(0, -0.2, 0)

Third, always be careful when you are trying to do offsets in cases where you want something to be offset and then returned to its original position. Just adding an offset and then subtracting an offset is dangerous. What happens if someone clicks your button again during the 0.2 second wait period? Your button will go down lower than expected, because it hasn't returned to the original position. What we will do instead is store the original orientation in a variable, apply an offset, then return the part back to its original orientation.

Altogether, with a bit of cleaning up, your code should look like this:

local originalCFrame = script.Parent.CFrame

function click()
    script.Parent.CFrame = originalCFrame + Vector3.new(0, -0.2, 0)
    wait(0.2)
    script.Parent.CFrame = originalCFrame
end

script.Parent.ClickDetector.MouseClick:connect(click)
Ad

Answer this question