3

Edit: This question is about Roblox Lua.

I'm using math.sin(tick()) to get a variable number and would like for it to always start at 0. Is this possible using math.sin? Is there something else I can use other than tick() to make this work?

Example:

for i = 1, 10 do
    local a = math.sin(tick())+1
    print(a)
    wait()
end
wait(1)
for i = 1, 10 do
    local a = math.sin(tick())+1
    print(a)
    wait()
end

My goal is to have this number start at 0 every time and then increase from there. So, it would start at 0 then increase to 2 and then decrease back to zero and continue modulating between 0 and 2 for as long as I continue calling it. Using the example above the number starts at any arbitrary number between 0 and 2.

JJJ
  • 83
  • 5

2 Answers2

2

I took a different approach and came up with this. It does exactly what I wanted to do with math.sin(tick()). If anyone knows other ways to accomplish this I would like to know.

    local n = 0
    local m = 0
    local Debounce = true

    local function SmoothStep(num)
        return num * num * (3 - 2 * num)
    end

    while Debounce do
        for i = 1, 100 do 
            wait()
            m = m+.01
            n = SmoothStep(m)
            print(n)
    if not Debounce then break end
        end

        for i = 1, 100 do
            wait() 
            m = m+.01
            n = SmoothStep(m)
            print(n)
    if not Debounce then break end
        end
    end
JJJ
  • 83
  • 5
  • 1
    It's not *exactly* the same. If you graph the printed values, you'll see a triangle wave rather than a sine wave. If that suits your purposes, that's fine. – Keith Thompson Jan 26 '16 at 02:12
  • 1
    I see. This does suit my purpose, but yeah, it's not exactly the same. I'm editing it and adding a smoothstep function to make it closer to a true sine wave. – JJJ Jan 26 '16 at 02:24
1

To non-Roblox users: tick() returns the local UNIX time. wait(t) yields the current thread for t seconds, the smallest possible interval being roughly 1/30th of a second.

Given that math.sin(0) equals 0, what you have to do is subtract the tick() inside the loop with the time the loop began at. This should make the expression inside math.sin start at roughly 0 at the beginning of the loop.

local loopstart = tick()
for i = 1, 10 do
    local a = math.sin(tick() - loopstart)+1
    print(a)
    wait()
end
xaxa
  • 26
  • 3
  • Thank you, xaxa. This is a working solution using math.sin(tick()). @KeithThompson made the same suggestion and it works. It starts at 1 instead of 0, but the most important part is that it starts at the same number every time. Perfect. I'll except this as the answer. – JJJ Jan 27 '16 at 21:42