Lua实现游戏震屏效果

原理就是对根UI座标做纵向和横向的偏移。纵向以正玄曲线、横向以余玄曲线的方式进行偏移。

直接上代码

仅供参考,如有错误望指正,互相学习。

[email protected] target 目标
[email protected] duration 震动时长(毫秒)
[email protected] interval 频率
[email protected] offset 最大偏移(即最大振幅)
[email protected] cb call back funciton
function c_shaker:reset(target, duration, interval, offset, cb)
    self.m_target = target;
    self.m_time = duration;
    self.m_interval = interval or 15;    
    self.m_maxOffset = offset or 5; --最大偏移量
    self.m_callBackFunc = cb;

    self.m_srcPos = {["x"] = target.x, ["y"] = target.y}; --目标原始位置
    self.m_activeTime = c.GetGameTime() + duration;
    self.m_nextShakeTime = c.GetGameTime() + self.m_interval;
    self.m_isStart = true;
end

function c_shaker:tick(t, dt)
    if not self.m_isStart then return end;
    if t <= self.m_activeTime then
        if t >= self.m_nextShakeTime then
            self.m_nextShakeTime = self.m_nextShakeTime + self.m_interval;
            self:doShake();
        end
    else
        self.m_isStart = false;
        self.m_target.x = self.m_srcPos.x;
        self.m_target.y = self.m_srcPos.y;
        if self.m_callBackFunc then
            self.m_callBackFunc();
        end
    end
end

function c_shaker:doShake()
    local radian = 2*math.pi*math.random();
    local x = self.m_srcPos.x + self.m_maxOffset * math.cos(radian);
    local y = self.m_srcPos.y + self.m_maxOffset * math.sin(radian);
    self.m_target.x = x;
    self.m_target.y = y;
end
点赞