南锋

南奔万里空,脱死锋镝余

Cocos Creator实现每日首次打开游戏功能

在 Cocos Creator 使用 TypeScript 判断每日首次登录时,你可以通过以下步骤实现:

存储上次登录时间:

使用本地存储(例如 localStorage 或 cc.sys.localStorage)来保存玩家的上次登录时间。

检查当天是否已登录:

在玩家登录时,获取当前日期并与上次登录的日期进行比较。如果日期不同,则表示这是当天的首次登录。

更新登录时间:

如果是首次登录,更新存储的上次登录时间为当前日期。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const LAST_LOGIN_KEY = "lastLoginDate";

function isFirstLoginToday(): boolean {
// 获取当前日期
const currentDate = new Date().toDateString();

// 从本地存储中获取上次登录日期
const lastLoginDate = cc.sys.localStorage.getItem(LAST_LOGIN_KEY);

// 判断是否为当天首次登录
if (lastLoginDate !== currentDate) {
// 如果不是今天,更新存储的登录日期并返回 true
cc.sys.localStorage.setItem(LAST_LOGIN_KEY, currentDate);
return true;
}

// 否则,返回 false 表示今天已经登录过
return false;
}

// 示例:在玩家登录时调用
if (isFirstLoginToday()) {
console.log("今日首次登录,给予奖励或执行相关逻辑。");
} else {
console.log("今天已经登录过。");
}

new Date().toDateString(): 获取当前日期的字符串形式。
cc.sys.localStorage.getItem(): 获取保存在本地存储中的上次登录日期。
cc.sys.localStorage.setItem(): 将当前日期保存到本地存储中,以便下次登录时比较。
通过这种方式,可以在游戏中轻松判断玩家是否为当天首次登录,从而触发每日奖励或其他相关逻辑。

+