squidGame/tgx-games-client/assets/module_arean/scripts/common/RoleManager.ts

86 lines
3.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Node, Vec3, Prefab, instantiate } from 'cc';
import { resLoader } from '../../../core_tgx/base/utils/ResLoader';
import { ModuleDef } from '../../../scripts/ModuleDef';
const { ccclass, property } = _decorator;
@ccclass('RoleManager')
export class RoleManager extends Component {
@property
private readonly roleCount: number = 36; // 生成角色数量
@property
private readonly minRadius: number = 3; // 最小半径
@property
private readonly maxRadius: number = 4; // 最大半径
@property
private readonly minRoleId: number = 1; // 最小角色ID
@property
private readonly maxRoleId: number = 5; // 最大角色ID
start() {
this.createRoles();
}
private formatRoleId(id: number): string {
return id.toString().length < 3 ? '0'.repeat(3 - id.toString().length) + id : id.toString();
}
private async createRoles() {
// 定义2个圆的半径和每个圆上的角色数量
const circles = [
{ radius: 4.5, count: 20 }, // 内圈20个
{ radius: 6, count: 16 } // 外圈16个
];
for (const circle of circles) {
const angleStep = 360 / circle.count;
for (let i = 0; i < circle.count; i++) {
const angle = i * angleStep + (Math.random() * 10 - 5); // 添加±5度随机偏移
const radius = circle.radius + (Math.random() * 0.3 - 0.15); // 添加±0.15半径随机偏移
// 计算位置
const angleInRadians = angle * Math.PI / 180;
const x = Math.sin(angleInRadians) * radius;
const z = Math.cos(angleInRadians) * radius;
// 随机角色ID1-5
const roleId = Math.floor(Math.random() * (this.maxRoleId - this.minRoleId + 1)) + this.minRoleId;
const roleIdStr = this.formatRoleId(roleId);
try {
const prefab = await new Promise<Prefab>((resolve, reject) => {
resLoader.load(ModuleDef.Arean, `common/role/Character${roleIdStr}`, (err: Error | null, res: Prefab) => {
if (err) reject(err);
else resolve(res as Prefab);
});
});
if (prefab) {
const role = instantiate(prefab);
role.setParent(this.node);
role.setPosition(new Vec3(x, 0, z));
// 让角色朝向稍微偏离圆心
const forward = new Vec3();
Vec3.subtract(forward, role.position, Vec3.ZERO);
const randomAngle = (Math.random() * 40 - 20) * Math.PI / 180; // 添加±20度随机朝向
const cos = Math.cos(randomAngle);
const sin = Math.sin(randomAngle);
const newX = forward.x * cos - forward.z * sin;
const newZ = forward.x * sin + forward.z * cos;
forward.x = newX;
forward.z = newZ;
forward.normalize();
role.forward = forward;
}
} catch (error) {
console.error(`Failed to load role prefab: common/role/Character${roleIdStr}`, error);
}
}
}
}
}