1

我目前正在为 Roblox 的PointLight对象编写方法。目前我正在编写方法来增加和减少BrightnessPointLight 的属性,但我已经靠在墙上试图获得我需要的公式。

程序需要在 DarkenSpeed(2 秒)的范围内从 Brightness (1) 循环到 FadedBrightness (.3)。我已经尝试在谷歌上搜索可能的解决方案,但我担心我正在寻找的东西太具体了。

这是一个代码片段:

local LightSource = {
  -- The value the PointLight's Brightness property will be when night and day,
  -- respectively.
  Brightness = 1,
  FadedBrightness = .3,

  -- How long (in seconds) it takes for the light source's brightness to be
  -- faded in/out.
  BrightenSpeed = 2,
  DarkenSpeed = 2
}

-- There is an IncreaseBrightness method, but that should be easy enough to
-- modify once the below is working.

function LightSource:DecreaseBrightness()
  -- self.Light refers to the PointLight instance.
  -- light.Brightness would be the current `Brightness` property.
  local light = self.Light

  -- Need to combine Brightness, FadedBrightness and DarkenSpeed into a formula
  -- for decrementing.

  local decrement = self.FadedBrightness / (self.Brightness * self.DarkenSpeed) -- 0.15, that won't work at all.

  while light.Brightness >= self.FadedBrightness do
    light.Brightness = light.Brightness - decrement
    wait()
  end
end

如果有任何更好的方法来实现这一点——或者甚至是不同的方法——我会全力以赴。我倾向于用我的代码获得隧道视野,除了当前的问题之外,我没有考虑任何其他事情。

4

2 回答 2

1

根据 Roblox 文档,wait() 在没有参数的情况下产生大约 1/30 秒: http ://wiki.roblox.com/index.php?title=Function_dump/Functions_specific_to_ROBLOX#Wait

您可以尝试使用 os.clock() 计算每个循环的差异并按比例缩放。未经测试的代码,但应该给出一个想法:

function LightSource:DecreaseBrightness()
  -- self.Light refers to the PointLight instance.
  -- light.Brightness would be the current `Brightness` property.
  local light = self.Light

  -- Need to combine Brightness, FadedBrightness and DarkenSpeed into a formula
  -- for decrementing.
  local strtBright=light.Brightness
  local _,strtTime=wait()
  local finTime=strt+self.DarkenSpeed
  while light.Brightness >= self.FadedBrightness do
    local _,currTime=wait()
    light.Brightness = math.max( self.FadedBrightness, strtBright - (strtBright-self.FadedBrightness) * ((curr-strtTime)/(finTime-strtTime)) )
  end
end
于 2014-05-09T01:02:33.780 回答
0

从 Odoth 的示例代码中,我切换wait()tick(),更改了变量名称以匹配我的编码风格,并将公式分成两行以提高可读性。

它运行良好,唯一的问题是它不能完全停止在 FadedBrightness(过去到大约 0.298),所以我在方法的底部添加了一条线来抵消不准确性。

时机完美,我对结果非常满意。

完成方法:

function LightSource:DecreaseBrightness()
  local light = self.Light
  local startBrightness = light.Brightness
  local startTime = tick()
  local endTime = startTime + self.DarkenSpeed

  while light.Brightness >= self.FadedBrightness do
    local currentTime = tick()
    local timer = (currentTime - startTime) / (endTime - startTime)
    local brightness = startBrightness - (startBrightness - self.FadedBrightness) * timer

    light.Brightness = brightness
    wait()
  end

  -- Set the brightness in case the loop spills over.
  light.Brightness = self.FadedBrightness
end
于 2014-05-09T23:33:44.413 回答