当前位置: 首页 > news >正文

第五课、Cocos Creator 中使用 TypeScript 基础介绍

本文主要是介绍在Cocos Creator 中开发的脚本 TypeScript  基础介绍,包含变量与数据类型、运算符、条件语句与循环结构、函数与作用域、面向对象编程基础

一、 变量与数据类型

1、变量声明

在 TypeScript 中,我们主要使用 let 和 const 声明变量:

let score: number = 100; // 可变变量
const playerName: string = "Player1"; // 不可变常量

2、基本数据类型

TypeScript 提供了多种基本数据类型:

// 布尔值
let isGameOver: boolean = false;// 数字
let hp: number = 100;
let mp: number = 50.5;// 字符串
let skillName: string = "Fire Ball";// 数组
let inventory: string[] = ["sword", "shield", "potion"];
let scores: Array<number> = [100, 200, 150];// 元组
let playerInfo: [string, number] = ["Warrior", 10];// 枚举 - 非常适合游戏状态管理
enum GameState {Loading,Playing,Paused,GameOver
}
let currentState: GameState = GameState.Loading;// Any - 当不确定类型时使用(应尽量避免)
let unknownValue: any = "could be anything";

二、运算符

TypeScript 支持 JavaScript 的所有运算符:

// 算术运算符
let sum: number = 10 + 5;
let difference: number = 10 - 5;
let product: number = 10 * 5;
let quotient: number = 10 / 5;
let remainder: number = 10 % 3;// 比较运算符
let isGreater: boolean = 10 > 5;
let isEqual: boolean = 10 === 10;// 逻辑运算符
let canAttack: boolean = (hp > 0) && (mp >= 10);

三、条件语句与循环结构

1、条件语句

// if-else
if (hp <= 0) {console.log("Player is dead");this.gameOver();
} else if (hp < 20) {console.log("Player health is critical");this.showLowHealthWarning();
} else {console.log("Player is healthy");
}// switch
switch (currentState) {case GameState.Loading:this.showLoadingScreen();break;case GameState.Playing:this.startGameplay();break;case GameState.Paused:this.pauseGame();break;default:this.handleUnknownState();
}

2、循环结构

// for循环
for (let i: number = 0; i < enemies.length; i++) {this.attackEnemy(enemies[i]);
}// for-of循环(遍历数组元素)
for (let item of inventory) {console.log("Inventory item:", item);
}// for-in循环(遍历对象属性)
for (let key in playerStats) {console.log(key, ":", playerStats[key]);
}// while循环
while (hp > 0 && enemies.length > 0) {this.fightNextEnemy();
}// do-while循环
do {this.tryToFindTreasure();
} while (!this.hasFoundTreasure);

四、 函数与作用域

1、函数定义

// 基本函数
function calculateDamage(attack: number, defense: number): number {return Math.max(0, attack - defense);
}// 箭头函数(适合回调)
const healPlayer = (amount: number): void => {hp += amount;if (hp > 100) hp = 100;this.updateHealthBar();
};// 可选参数和默认参数
function useItem(itemId: number, quantity: number = 1): boolean {// 使用物品的逻辑return true; // 使用成功
}

2、作用域

class Player {private health: number = 100; // 私有属性,只能在类内部访问public name: string; // 公共属性,可以在任何地方访问constructor(name: string) {this.name = name;}// 公共方法public takeDamage(damage: number): void {this.health -= damage;if (this.health < 0) this.health = 0;}// 私有方法private die(): void {console.log(`${this.name} has died`);}
}

五、 面向对象编程基础

1、类与对象

// 基类: 游戏实体
class Entity {protected id: number;public position: cc.Vec2;constructor(id: number, position: cc.Vec2) {this.id = id;this.position = position;}public moveTo(position: cc.Vec2): void {this.position = position;}
}// 派生类: 玩家
class Player extends Entity {private health: number;private level: number;constructor(id: number, position: cc.Vec2) {super(id, position);this.health = 100;this.level = 1;}public attack(target: Enemy): void {console.log(`Player ${this.id} attacks ${target.id}`);// 攻击逻辑}// 静态方法public static createNewPlayer(): Player {return new Player(Date.now(), cc.v2(0, 0));}
}// 派生类: 敌人
class Enemy extends Entity {private strength: number;constructor(id: number, position: cc.Vec2, strength: number) {super(id, position);this.strength = strength;}public attack(target: Player): void {console.log(`Enemy ${this.id} attacks player ${target.id}`);// 攻击逻辑}
}

2、接口

// 定义可攻击对象的接口
interface Attackable {health: number;takeDamage(damage: number): void;
}// 定义可移动对象的接口
interface Movable {position: cc.Vec2;moveTo(position: cc.Vec2): void;
}// 实现接口的类
class Character implements Attackable, Movable {public health: number = 100;public position: cc.Vec2 = cc.v2(0, 0);public takeDamage(damage: number): void {this.health -= damage;}public moveTo(position: cc.Vec2): void {this.position = position;}
}

六、在 Cocos Creator 中使用

const { ccclass, property } = cc._decorator;@ccclass
export default class PlayerController extends cc.Component {@property(cc.Integer)private moveSpeed: number = 200;@property(cc.Label)private healthLabel: cc.Label = null;private health: number = 100;onLoad() {// 初始化逻辑}start() {this.updateHealthDisplay();}update(dt: number) {this.handleMovement(dt);}private handleMovement(dt: number): void {// 处理移动逻辑}private updateHealthDisplay(): void {if (this.healthLabel) {this.healthLabel.string = `Health: ${this.health}`;}}public takeDamage(amount: number): void {this.health -= amount;this.updateHealthDisplay();if (this.health <= 0) {this.die();}}private die(): void {console.log("Player died");// 处理玩家死亡逻辑}
}

七、总结

TypeScript 为 Cocos Creator 开发带来了类型安全、更好的代码组织和智能提示等优势。通过掌握变量与数据类型、运算符、流程控制、函数与作用域以及面向对象编程基础,您可以编写出更健壮、更易维护的游戏代码。

在实际开发中,建议充分利用 TypeScript 的类型系统,定义清晰的接口和类型注解,这将大大提高代码质量和开发效率。


文章转载自:

http://SjyrEWBb.pjxtq.cn
http://fs0mMQX8.pjxtq.cn
http://m79wr5P6.pjxtq.cn
http://umZD5GSB.pjxtq.cn
http://7OxlAngk.pjxtq.cn
http://oEYmxnig.pjxtq.cn
http://GxOS8k3G.pjxtq.cn
http://YLiTekZU.pjxtq.cn
http://V0vd6JYD.pjxtq.cn
http://MjdLdPbg.pjxtq.cn
http://mJqcoQEO.pjxtq.cn
http://Er0eLB7G.pjxtq.cn
http://QFV31ul5.pjxtq.cn
http://nen69hPk.pjxtq.cn
http://Fz57FXRT.pjxtq.cn
http://vLYCDdUs.pjxtq.cn
http://hS3QVfzQ.pjxtq.cn
http://j5n9opCl.pjxtq.cn
http://JjXUFtxQ.pjxtq.cn
http://wcrwjww2.pjxtq.cn
http://r4476nI0.pjxtq.cn
http://AliOS0VX.pjxtq.cn
http://jlCsVNjI.pjxtq.cn
http://ThIw5U51.pjxtq.cn
http://ew7OQP3w.pjxtq.cn
http://cHeagF5O.pjxtq.cn
http://8LsVRyqE.pjxtq.cn
http://Ro9azc6Y.pjxtq.cn
http://03d9a3Pn.pjxtq.cn
http://ethYJILf.pjxtq.cn
http://www.dtcms.com/a/386633.html

相关文章:

  • 09MYSQL视图:安全高效的虚拟表
  • R 语言本身并不直接支持 Python 中 f“{series_matrix}.txt“ 这样的字符串字面量格式化(f-string)语法 glue函数
  • 【AI论文】AgentGym-RL:通过多轮强化学习训练大语言模型(LLM)智能体以实现长期决策制定
  • Win11本地jdk1.8和jdk17双版本切换运行方法
  • vue3 使用print.js打印el-table全部数据
  • Vue 3 + TypeScript + 高德地图 | 实战:多车轨迹回放(点位驱动版)
  • [vue]创建表格并实现筛选和增删改查功能
  • JVM-运行时内存
  • 后缀树跟字典树的区别
  • LanceDB向量数据库
  • RabbitMQ 异步化抗洪实战
  • 《Java集合框架核心解析》
  • 二维码生成器
  • OSI七层模型
  • 【原创·极简新视角剖析】【组局域网】设备在同一局域网的2个条件
  • 第8课:高级检索技术:HyDE与RAG-Fusion原理与DeepSeek实战
  • Windows 命令行:路径的概念,绝对路径
  • 异常检测在网络安全中的应用
  • 【ubuntu】ubuntu 22.04 虚拟机中扩容操作
  • 【数值分析】05-绪论-章节课后1-7习题及答案
  • Java NIO 核心机制与应用
  • Roo Code 诊断集成功能:智能识别与修复代码问题
  • ANA Pay不再接受海外信用卡储值 日eShop生路再断一条
  • 一阶惯性环节的迭代公式
  • AWS 热门服务(2025 年版)
  • 拷打字节算法面试官之-深入c语言递归算法
  • Vehiclehal的VehicleService.cpp
  • 【传奇开心果系列】基于Flet框架实现的允许调整大小的开关自定义组件customswitch示例模板特色和实现原理深度解析
  • 八股整理xdsm
  • SpringBoot 配置文件详解:从基础语法到实战应用