本帖最后由 空伊伊 于 2023-3-17 22:11 编辑
一个脚本帮把这些功能都实现(甚至UI都不用你写)!可以看这个代码学习哈,不懂的地方评论区回复我就行!
脚本的用法:直接拖到场景上即可
@Core.Class
export default class CoinGame extends Core.Script {
/**已获取的金币数量 */
coinCount: number = 0
textUI:UI.TextBlock
/** 当脚本被实例后,会在第一帧更新前调用此函数 */
protected async onStart(): Promise<void> {
if (SystemUtil.isClient()) {
// 创建UI
this.creatUI()
// 一上线,向服务器请求数据
Events.dispatchToServer("reqLoadData")
// 收到服务器传来的数据,开始生成金币
Events.addServerListener("LoadData", (dataCount: number) => {
console.log("收到请求")
this.coinCount = dataCount
this.textUI.text = "当前金币数:"+this.coinCount
// 开始循环生成金币
let inter = setInterval(() => {
this.creatCoin()
}, 3000)
})
}
if (SystemUtil.isServer()) {
// 设置存档环境
DataStorage.setTemporaryStorage(SystemUtil.isPIE)
// 监听客户端请求数据的请求
Events.addClientListener("reqLoadData", async (player: Gameplay.Player) => {
let data = await DataStorage.asyncGetPlayerData(player)
if (data) {
Events.dispatchToClient(player, "LoadData", data)
} else {
Events.dispatchToClient(player, "LoadData", 0)
}
})
// 监听客户端存储数据的请求
Events.addClientListener("SaveData", async (player: Gameplay.Player, coinCount: number) => {
await DataStorage.asyncSetPlayerData(player, coinCount)
})
}
}
/**创建一个金币 */
private async creatCoin() {
console.log("创建金币")
// 创建触发器
let trigger = (await Core.GameObject.asyncSpawn({ "guid": "Trigger" })) as Gameplay.Trigger
// 设置缩放
trigger.worldScale = new Type.Vector(0.5, 1.75, 1.75)
AssetUtil.asyncDownloadAsset("13014")
// 创建金币
let coin = (await Core.GameObject.asyncSpawn({ "guid": "13014" })) as Gameplay.Trigger
// 设置缩放
coin.worldScale = new Type.Vector(1.5, 0.4, 0.4)
// 将金币attach到触发器上
coin.attachToGameObject(trigger)
// 给触发器添加逻辑
trigger.onEnter.add(this.onTriggerEnter.bind(this, trigger))
// 随机让触发器出现在一个位置
trigger.worldLocation = new Type.Vector(1000 * Math.random(), 1000 * Math.random(), 50)
}
private onTriggerEnter(trigger: Gameplay.Trigger, other: Core.GameObject) {
// 如果是人形对象,且人形对象是自己,销毁触发器,并增加获取到的金币数
if (other instanceof Gameplay.Character) {
if (other == Gameplay.getCurrentPlayer().character) {
this.addCoin()
// 因为金币被attach到了trigger上,所以删除trigger,金币也就会被删除
trigger.destroy()
}
}
}
private addCoin() {
this.coinCount++
this.textUI.text = "当前金币数:"+this.coinCount
console.log("已获得金币数:" + this.coinCount)
// 这里需要改进一下,当频率过高,可能会导致存储失败。(可以在论坛搜索“数据存储原理”进行了解)
Events.dispatchToServer("SaveData", this.coinCount)
}
private creatUI(){
// 创建一个UI对象
let ui = UI.UserWidget.newObject();
// 将UI添加到屏幕上
ui.addToViewport(1)
// 创建一个画布组件
let rootCanvas = UI.Canvas.newObject()
rootCanvas.size = new Type.Vector2(1920, 1080);
rootCanvas.position = Type.Vector2.zero
// 将Ui的根画布设置为rootCanvas
ui.rootContent = rootCanvas
// 创建一个UI添加到画布上
this.textUI = UI.TextBlock.newObject(rootCanvas)
this.textUI.position = new Type.Vector2(1600, 200)
this.textUI.size = new Type.Vector2(1000, 200)
this.textUI.fontColor = Type.LinearColor.red
}
}
|