關於cocos2dx lua版本中遊戲時間顯示問題

2021-07-01 22:11:14 字數 1456 閱讀 1023

時間顯示問題說白了就是時差問題(下面**片斷是以lua指令碼寫的)。

一般來說,遊戲中時間是以遊戲伺服器時間為準。遊戲登入時,會從伺服器接收乙個時間,普遍方案是接收乙個時間戳,然後客戶端自己維護這個時間戳。有時,客戶端會進行這個時間的顯示:

local servertimestamp = ******xx  --這個是服務端發給客戶端維護的時間戳

local servertimezone = ***x      --這個是服務端時間的時區差值(也是由服務端發給客戶端)

local currentdatetime = os.date("*t",servertimestamp)

print("year="..currentdatetime.year)

print("month="..currentdatetime.month)

print("day="..currentdatetime.day)

print("hour="..currentdatetime.hour)

print("min="..currentdatetime.min)

print("sec="..currentdatetime.sec)

如果你的遊戲服務端時間的時區是東八區,且跑上面**的機子的時區也是東八區,你可能會非常樂意地看到,列印出來的時間與服務端時間是一致的;但是用來跑上面**的機子的時區不是東八區,如乙個日本人使用他機子來跑你的程式(他的機子時區是東九區),這時會看到列印出來的時間比這遊戲服務端的時間快了1個小時,這肯定是錯誤的。

為什麼會這樣?

原來上面呼叫os.date()時會把當前裝置的時區也關聯上去。所以在東八區裝置下跑完全是正確的。但你不可能指定別人使用固定時區的機子來跑你的程式吧,那怎辦呢?

-- compute the difference in seconds between local time and utc.

local function get_timezone()

local now = os.time()

return os.difftime(now, os.time(os.date("!*t", now)))

endlocal localtimezone = get_timezone()

local timezoned = servertimezone - localtimezone  --計算出服務端時區與客戶端時區差值

local currentdatetime = os.date("*t",servertimestamp + timezoned)

這時你會發現,無論你使用東八區、東九區或者其它時區的機子去跑,它都正確地列印出這個伺服器的時間。

擴充套件一下來說,只要你做了這個時區的差值處理,無論伺服器的時區是哪個,無論客戶端的時區是哪個,客戶端都能正確地顯示伺服器的時間。

再擴充套件一下來說,無論是哪個cocos2dx的版本,無論是使用哪個遊戲引擎框架,都應該在處理時間上做類似上面的時區處理,讓客戶端能夠正確地顯示服務端的時間。

Cocos2d x Lua基本操作

1.lua庫引用 目錄新增 lua lua luajit include lib新增 lua51.lib 2.開啟lua庫 示例 lua state pl lua open luaopen base pl luaopen math pl luaopen string pl 3.讀取lua值 示例 1...

cocos2dx lua優化總結

渲染效率 紋理格式 執行效率 記憶體 包大小 cpp view plain copy 安卓啟用4444紋理 iftargetplatform cc.platform os android then cc.texture2d setdefaultalphapixelformat cc.texture2...

Cocos2dx lua 啟動流程

cocos2dx 版本 3.x,工具 vs2013 babelua外掛程式 1.lua工具,babelua 2.cocos2dx 建立lua工程 windows 7下,配置好cocos2dx環境後,使用命令列建立專案。cocos new mylua1 p com.your company.mygam...