添加登录功能

This commit is contained in:
zpx committed 2026-11-20 15:13:11 +08:00
commit a3f61a29d0
120 files changed
+3974

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
/** 登录边界与可注入端口。 / Login contracts and injectable ports. */
export interface GuestSettings {
origin: string;
product: string;
deviceType: 'iphone' | 'ipad';
registerDevice: string;
timeoutMs: number;
}
export interface GuestSession { guestId: string; token: string; expires: number }
export interface TextStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
}
export interface GuestAccountStore {
identity(create: () => string): string;
save(session: GuestSession): void;
}
export interface GuestPayload {
guest_id: string;
pkg: string;
device_type: 'iphone' | 'ipad';
register_device: string;
install_fb: boolean;
gyroscope_not_spinning: boolean;
}
export interface GuestSigner {
headers(payload: GuestPayload): Record<string, string>;
}
export interface GuestTransport {
post(path: string, body: object, headers: Record<string, string>, signal?: AbortSignal): Promise<Record<string, unknown>>;
}
export interface GuestLogin { signIn(signal?: AbortSignal): Promise<GuestSession> }
export type GuestFailure = 'configuration' | 'identity' | 'storage' | 'network' | 'timeout' | 'cancelled' | 'response' | 'verification' | 'rejected';
/** 只向界面提供固定消息,避免泄漏服务器原文或凭据。 / Expose fixed messages, never raw server data or credentials. */
export class GuestError extends Error {
constructor(readonly kind: GuestFailure, message: string) { super(message); this.name = 'GuestError'; }
}
export function assertNotCancelled(signal?: AbortSignal): void {
if (signal?.aborted) throw new GuestError('cancelled', 'Sign-in cancelled.');
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "a16fec42-51b1-45d6-b6c0-8746ded67408",
"files": [],
"subMetas": {},
"userData": {}
}
+49
View File
@@ -0,0 +1,49 @@
import { assertNotCancelled, GuestError, GuestTransport } from './GuestContracts';
/** 请求与响应读取共用期限,取消后隔离迟到结果。 / One deadline covers fetch and response parsing; ignore late results after cancellation. */
export class GuestHttpClient implements GuestTransport {
constructor(private readonly origin: string, private readonly timeoutMs: number, private readonly fetcher: typeof fetch) {
if (!/^https:\/\/[^\s/@?#:\\]+(?::\d+)?$/.test(origin) || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new GuestError('configuration', 'Guest service configuration is unavailable.');
}
}
async post(path: string, body: object, headers: Record<string, string>, signal?: AbortSignal): Promise<Record<string, unknown>> {
assertNotCancelled(signal);
const request = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
let cancel = () => {};
const interruption = new Promise<never>((_, reject) => {
cancel = () => { reject(new GuestError('cancelled', 'Sign-in cancelled.')); request.abort(); };
signal?.addEventListener('abort', cancel, { once: true });
timer = setTimeout(() => { reject(new GuestError('timeout', 'Sign-in timed out. Please retry.')); request.abort(); }, this.timeoutMs);
});
try {
return await Promise.race([interruption, this.exchange(path, body, headers, request.signal)]);
} catch (error) {
if (error instanceof GuestError) throw error;
throw new GuestError('network', 'Unable to connect. Please check your connection and retry.');
} finally {
if (timer !== undefined) clearTimeout(timer);
signal?.removeEventListener('abort', cancel);
}
}
private async exchange(path: string, body: object, headers: Record<string, string>, signal: AbortSignal): Promise<Record<string, unknown>> {
const response = await this.fetcher(this.origin + path, {
method: 'POST', headers: { 'Content-Type': 'application/json', ...headers },
credentials: 'omit', body: JSON.stringify(body), signal,
});
if (!response.ok) throw new GuestError('network', 'Guest service is unavailable. Please retry.');
let data: unknown;
try { data = await response.json(); }
catch { throw new GuestError('response', 'Invalid sign-in response. Please retry.'); }
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new GuestError('response', 'Invalid sign-in response. Please retry.');
const result = data as Record<string, unknown>;
if (result.code !== 0) {
if (result.code === 401 && typeof result.msg === 'string' && /\brequest_sign_invalid\b/.test(result.msg)) {
throw new GuestError('verification', 'Sign-in verification failed. Check the device clock or signing configuration.');
}
throw new GuestError('rejected', 'Guest sign-in was rejected. Please retry.');
}
return result;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "9ca9729a-e1df-45ea-81b2-ef11b40f297f",
"files": [],
"subMetas": {},
"userData": {}
}
+27
View File
@@ -0,0 +1,27 @@
import { _decorator, Button, Component, Label, sys } from 'cc';
const { ccclass, property } = _decorator;
/** 法律链接单独绑定,不混入认证服务;缺地址时显示真实状态。 / Bind legal links separately from authentication and report missing URLs honestly. */
@ccclass('GuestLegalLinks')
export class GuestLegalLinks extends Component {
@property({ type: Button }) privacyButton: Button | null = null;
@property({ type: Button }) termsButton: Button | null = null;
@property({ type: Label }) notice: Label | null = null;
@property privacyUrl = '';
@property termsUrl = '';
onLoad(): void {
this.privacyButton?.node.on(Button.EventType.CLICK, this.openPrivacy, this);
this.termsButton?.node.on(Button.EventType.CLICK, this.openTerms, this);
}
private openPrivacy(): void { this.open(this.privacyUrl, 'Privacy policy is not available yet.'); }
private openTerms(): void { this.open(this.termsUrl, 'Terms of service are not available yet.'); }
private open(url: string, unavailable: string): void {
if (/^https:\/\/[^\s]+$/i.test(url)) { sys.openURL(url); return; }
// 未配置不伪造页面,也不启动登录或覆盖游客会话。 / Never invent a page, trigger login or overwrite the guest session when unconfigured.
if (this.notice) { this.notice.string = unavailable; this.notice.node.active = true; }
}
onDestroy(): void {
if (this.privacyButton?.isValid) this.privacyButton.node.off(Button.EventType.CLICK, this.openPrivacy, this);
if (this.termsButton?.isValid) this.termsButton.node.off(Button.EventType.CLICK, this.openTerms, this);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "7f182094-3816-4409-b492-771b059cc23b",
"files": [],
"subMetas": {},
"userData": {}
}
@@ -0,0 +1,53 @@
import { GuestError, GuestLogin, GuestSession } from './GuestContracts';
export type LoginPhase = 'idle' | 'signing-in' | 'authenticated' | 'failed';
export interface LoginState { phase: LoginPhase; message: string; enabled: boolean }
export interface LoginViewPort { render(state: LoginState): void }
/** 独立于引擎的交互状态机,方便测试连点与销毁。 / Engine-independent interaction state machine for repeated-click and lifecycle tests. */
export class GuestLoginPresenter {
private operation: AbortController | null = null;
private disposed = false;
private authenticated = false;
constructor(private readonly view: LoginViewPort, private readonly service: () => GuestLogin,
private readonly completed: (session: GuestSession) => void) {}
async submit(): Promise<void> {
if (this.disposed || this.operation || this.authenticated) return;
if (typeof AbortController === 'undefined') {
this.view.render({ phase: 'failed', message: 'Secure sign-in is unavailable on this platform.', enabled: true });
return;
}
const operation = new AbortController();
this.operation = operation;
let authenticated: GuestSession | null = null;
try {
this.view.render({ phase: 'signing-in', message: 'Signing in...', enabled: false });
const session = await this.service().signIn(operation.signal);
if (!this.isCurrent(operation)) return;
this.authenticated = true;
authenticated = session;
} catch (error) {
if (!this.isCurrent(operation)) return;
const message = error instanceof GuestError ? error.message : 'Unable to sign in. Please retry.';
this.view.render({ phase: 'failed', message, enabled: true });
} finally {
if (this.operation === operation) this.operation = null;
}
if (authenticated) {
// 成功通知异常不能回滚已保存的认证状态。 / Presentation failures must not turn committed authentication into a login failure.
try {
this.view.render({ phase: 'authenticated', message: 'Signed in successfully.', enabled: false });
this.completed(authenticated);
} catch { /* 保留已认证状态且不输出会话。 / Retain authentication without logging the session. */ }
}
}
cancel(): void {
const operation = this.operation;
this.operation = null;
operation?.abort();
if (!this.disposed && !this.authenticated) this.view.render({ phase: 'idle', message: '', enabled: true });
}
dispose(): void { this.disposed = true; this.cancel(); }
private isCurrent(operation: AbortController): boolean {
return !this.disposed && this.operation === operation && !operation.signal.aborted;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "4f3bdd87-5f8e-4b02-8fcf-1f852e5170c1",
"files": [],
"subMetas": {},
"userData": {}
}
+43
View File
@@ -0,0 +1,43 @@
import { assertNotCancelled, GuestAccountStore, GuestError, GuestLogin, GuestPayload, GuestSession, GuestSettings, GuestSigner, GuestTransport } from './GuestContracts';
import { GUEST_REGISTRATION_PATH } from './GuestSignature';
/** 两步认证的应用服务;不依赖场景或平台全局对象。 / Two-step authentication service independent of scenes and platform globals. */
export class GuestLoginService implements GuestLogin {
private current: Promise<GuestSession> | null = null;
constructor(private readonly settings: GuestSettings, private readonly accounts: GuestAccountStore,
private readonly signer: GuestSigner, private readonly transport: GuestTransport, private readonly makeIdentity: () => string) {}
signIn(signal?: AbortSignal): Promise<GuestSession> {
// 合并请求由首次调用者拥有;已取消的新调用者不加入等待。 / The first caller owns a coalesced request; an already-cancelled caller never joins.
if (signal?.aborted) return Promise.reject(new GuestError('cancelled', 'Sign-in cancelled.'));
if (this.current) return this.current;
const operation = this.authenticate(signal);
this.current = operation;
const release = () => { if (this.current === operation) this.current = null; };
void operation.then(release, release);
return operation;
}
private async authenticate(signal?: AbortSignal): Promise<GuestSession> {
assertNotCancelled(signal);
if (!this.settings.product.trim() || !['iphone', 'ipad'].includes(this.settings.deviceType) ||
!['web', 'android-google', 'ios'].includes(this.settings.registerDevice)) {
throw new GuestError('configuration', 'Guest service configuration is unavailable.');
}
const guestId = this.accounts.identity(this.makeIdentity);
const body: GuestPayload = {
guest_id: guestId, pkg: this.settings.product, device_type: this.settings.deviceType,
register_device: this.settings.registerDevice, install_fb: false, gyroscope_not_spinning: false,
};
await this.transport.post(GUEST_REGISTRATION_PATH, body, this.signer.headers(body), signal);
assertNotCancelled(signal);
// 换 token 不携带签名或认证头;始终使用同一游客身份。 / Exchange without signature/auth headers using the same identity.
const response = await this.transport.post('/account/login', { guest_id: guestId, pkg: this.settings.product }, {}, signal);
assertNotCancelled(signal);
const value = response.data;
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new GuestError('response', 'Invalid sign-in response. Please retry.');
const data = value as Record<string, unknown>;
if (typeof data.token !== 'string' || !data.token.trim()) throw new GuestError('response', 'Invalid sign-in response. Please retry.');
const session: GuestSession = { guestId, token: data.token, expires: typeof data.expires === 'number' && Number.isFinite(data.expires) ? data.expires : 0 };
this.accounts.save(session);
return session;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "d1086204-c49f-4b6a-b552-41c197bc2c48",
"files": [],
"subMetas": {},
"userData": {}
}
+40
View File
@@ -0,0 +1,40 @@
import { _decorator, Button, Component, Label } from 'cc';
import type { GuestSession } from './GuestContracts';
import { GuestLoginPresenter, LoginState, LoginViewPort } from './GuestLoginPresenter';
import { createGuestLogin } from './GuestRuntime';
const { ccclass, property } = _decorator;
/** 场景适配组件,只负责控件绑定与状态展示。 / Scene adapter responsible only for control bindings and rendering state. */
@ccclass('GuestLoginView')
export class GuestLoginView extends Component implements LoginViewPort {
static readonly AUTHENTICATED = 'guest-authenticated';
@property({ type: Button }) guestButton: Button | null = null;
@property({ type: Label }) statusLabel: Label | null = null;
private presenter: GuestLoginPresenter | null = null;
private session: GuestSession | null = null;
get signedIn(): boolean { return this.session !== null; }
onLoad(): void {
if (!this.guestButton || !this.statusLabel) return;
this.presenter = new GuestLoginPresenter(this, createGuestLogin, session => {
this.session = session;
// 事件不包含 token,后续流程按需读取受控会话存储。 / Do not expose the token in UI events; future flow can read the session store.
this.node.emit(GuestLoginView.AUTHENTICATED);
});
this.guestButton.node.on(Button.EventType.CLICK, this.submit, this);
this.render({ phase: 'idle', message: '', enabled: true });
}
private submit(): void { void this.presenter?.submit(); }
render(state: LoginState): void {
if (this.guestButton) this.guestButton.interactable = state.enabled;
if (this.statusLabel) {
this.statusLabel.string = state.message;
this.statusLabel.node.active = state.message.length > 0;
}
}
onDisable(): void { this.presenter?.cancel(); }
onDestroy(): void {
this.presenter?.dispose();
if (this.guestButton?.isValid) this.guestButton.node.off(Button.EventType.CLICK, this.submit, this);
this.session = null;
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "e7144023-5b32-4c59-89e8-be661c99fe09",
"files": [],
"subMetas": {},
"userData": {}
}
+36
View File
@@ -0,0 +1,36 @@
import { sys } from 'cc';
import signing from '../../../common-key/common_key.json';
import { GuestError, GuestLogin, GuestSettings } from './GuestContracts';
import { GuestHttpClient } from './GuestHttpClient';
import { GuestLoginService } from './GuestLoginService';
import { GuestSessionStore } from './GuestSessionStore';
import { HmacGuestSigner } from './GuestSignature';
/** 沿用已确认的服务配置,本地身份使用 Fruit Pop 命名空间。 / Reuse the approved service configuration with a Fruit Pop storage namespace. */
export const GUEST_SERVICE = { origin: 'https://gate.vivarisdigitalgate.com', product: 'VeryWellSlots', timeoutMs: 30000 } as const;
export function guestDeviceType(userAgent: string, touchPoints: number): 'iphone' | 'ipad' {
return /iPad|Tablet/i.test(userAgent) || (/Macintosh/i.test(userAgent) && touchPoints > 1) ? 'ipad' : 'iphone';
}
/** 只能使用安全随机源,不降级到 Math.random。 / Require secure randomness; never fall back to Math.random. */
export function secureGuestId(): string {
if (!globalThis.crypto || typeof globalThis.crypto.getRandomValues !== 'function') {
throw new GuestError('configuration', 'Secure sign-in is unavailable on this platform.');
}
const bytes = new Uint8Array(16);
globalThis.crypto.getRandomValues(bytes);
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
}
/** 组合根:在这里连接配置、平台能力与独立领域服务。 / Composition root connecting configuration, platform ports and the independent service. */
export function createGuestLogin(): GuestLogin {
if (typeof globalThis.fetch !== 'function' || typeof AbortController === 'undefined') {
throw new GuestError('configuration', 'Network sign-in is unavailable on this platform.');
}
const settings: GuestSettings = {
...GUEST_SERVICE,
deviceType: typeof navigator === 'undefined' ? 'iphone' : guestDeviceType(navigator.userAgent, navigator.maxTouchPoints || 0),
registerDevice: sys.isNative ? (sys.os === sys.OS.ANDROID ? 'android-google' : 'ios') : 'web',
};
return new GuestLoginService(settings, new GuestSessionStore(sys.localStorage, settings.origin, settings.product),
new HmacGuestSigner(signing.key, secureGuestId),
new GuestHttpClient(settings.origin, settings.timeoutMs, globalThis.fetch.bind(globalThis)), secureGuestId);
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "bd61a17b-2d5d-4c42-b294-56d7d1faa08c",
"files": [],
"subMetas": {},
"userData": {}
}
+34
View File
@@ -0,0 +1,34 @@
import { GuestAccountStore, GuestError, GuestSession, TextStorage } from './GuestContracts';
/** 按产品和服务隔离身份,成功会话单独提交。 / Isolate identities by product/service and commit successful sessions separately. */
export class GuestSessionStore implements GuestAccountStore {
readonly identityKey: string;
readonly sessionKey: string;
constructor(private readonly storage: TextStorage, origin: string, product: string) {
const scope = encodeURIComponent(`${origin.replace(/\/+$/, '')}|${product}`);
this.identityKey = `fruit-pop.auth.identity.v1.${scope}`;
this.sessionKey = `fruit-pop.auth.session.v1.${scope}`;
}
identity(create: () => string): string {
try {
const existing = this.storage.getItem(this.identityKey);
const identity = existing ?? create();
if (typeof identity !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(identity)) {
throw new GuestError('identity', 'Unable to restore a secure guest identity.');
}
if (existing === null) this.writeVerified(this.identityKey, identity);
return identity;
} catch (error) { throw this.storageError(error); }
}
save(session: GuestSession): void {
try { this.writeVerified(this.sessionKey, JSON.stringify(session)); }
catch (error) { throw this.storageError(error); }
}
private writeVerified(key: string, text: string): void {
this.storage.setItem(key, text);
if (this.storage.getItem(key) !== text) throw new GuestError('storage', 'Unable to save guest data. Please retry.');
}
private storageError(error: unknown): GuestError {
return error instanceof GuestError ? error : new GuestError('storage', 'Guest storage is unavailable. Please retry.');
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "4c8e112f-a077-4804-8336-a8e2fb14fbf3",
"files": [],
"subMetas": {},
"userData": {}
}
+28
View File
@@ -0,0 +1,28 @@
import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha2';
import { GuestError, GuestPayload, GuestSigner } from './GuestContracts';
export const GUEST_REGISTRATION_PATH = '/account/v2/guest/login';
/** 协议签名,不负责发送请求或读取配置。 / Protocol signing without transport or configuration access. */
export class HmacGuestSigner implements GuestSigner {
constructor(private readonly secret: string, private readonly nonce: () => string, private readonly clock: () => number = Date.now) {
if (typeof secret !== 'string' || !secret.trim()) throw new GuestError('configuration', 'Guest signing configuration is unavailable.');
}
headers(payload: GuestPayload): Record<string, string> {
const timestamp = String(Math.floor(this.clock() / 1000));
const nonce = this.nonce();
if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp)) || Number(timestamp) <= 0 || !/^[a-zA-Z0-9-]{16,128}$/.test(nonce)) {
throw new GuestError('configuration', 'Unable to prepare a secure sign-in request.');
}
// 仅签白名单;false 必须参与,空 uid 是第五行。 / Sign only allowed fields; include false and the empty fifth uid line.
const fields: Record<string, string> = {
guest_id: payload.guest_id, pkg: payload.pkg, device_type: payload.device_type,
register_device: payload.register_device, install_fb: String(payload.install_fb),
gyroscope_not_spinning: String(payload.gyroscope_not_spinning),
};
const canonical = Object.keys(fields).filter(key => fields[key] !== '').sort().map(key => `${key}=${fields[key]}`).join('&');
const message = ['POST', GUEST_REGISTRATION_PATH, timestamp, nonce, '', canonical].join('\n');
const signature = Array.from(hmac(sha256, this.secret, message), value => value.toString(16).padStart(2, '0')).join('');
return { 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Sign': signature };
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "ba15ae6b-94f5-454f-a584-b5decaa0f66e",
"files": [],
"subMetas": {},
"userData": {}
}
@@ -0,0 +1,71 @@
import { _decorator, Button, Canvas, Color, Component, Label, Node, Sprite, UITransform, Widget } from 'cc';
import { EDITOR } from 'cc/env';
const { ccclass, executeInEditMode, property } = _decorator;
/** 仅按显式开关校准已存在节点,不在运行时重建界面。 / Explicit editor-only calibration of existing nodes; never rebuild UI at runtime. */
@ccclass('WelcomeLayoutAuthoring')
@executeInEditMode
export class WelcomeLayoutAuthoring extends Component {
@property
get applyReferenceLayout(): boolean { return false; }
set applyReferenceLayout(value: boolean) {
if (!EDITOR || !value) return;
const canvas = this.node;
const group = this.child(canvas, 'WelcomeComposition');
const widget = canvas.getComponent(Widget);
if (widget) { widget.alignFlags = 0; widget.enabled = false; }
// 保存的设计画布与项目设置保持一致,运行适配仍由独立组件负责。 / Persist the design canvas; the viewport component owns runtime adaptation.
canvas.getComponent(UITransform)!.setContentSize(1080, 1920);
canvas.setPosition(540, 960, 0);
const camera = canvas.getChildByName('Camera');
if (!canvas.getComponent(Canvas) || !camera) throw new Error('Welcome canvas is unavailable.');
const backdrop = this.child(canvas, 'OrchardBackdrop');
this.box(backdrop, 0, 0, 1080, 1920);
backdrop.setSiblingIndex(1);
this.sprite(backdrop);
this.box(this.child(group, 'BrandMark'), 4, 466.5, 982, 643);
this.box(this.child(group, 'FruitArrangement'), -7.5, -78, 991, 456);
this.box(this.child(group, 'GuestAccess'), -1.5, -460, 1027, 268);
for (const name of ['BrandMark', 'FruitArrangement', 'GuestAccess']) this.sprite(this.child(group, name));
const button = this.child(group, 'GuestAccess').getComponent(Button);
if (button) { button.transition = Button.Transition.SCALE; button.zoomScale = .97; }
this.text(this.child(group, 'GuestReassurance'), 'No account needed', 0, -618, 780, 90, 56);
this.text(this.child(group, 'PrivacyLink'), 'Privacy Policy', -190, -765, 300, 88, 38, true);
this.text(this.child(group, 'TermsLink'), 'Terms of Service', 179, -765, 340, 88, 38, true);
this.text(this.child(group, 'LegalDivider'), '|', -10, -765, 28, 76, 56);
this.child(group, 'LegalDivider').getComponent(Label)!.color = new Color(236, 0, 136, 255);
const status = this.child(group, 'AuthenticationStatus');
this.text(status, '', 0, -692, 960, 50, 25);
status.active = false;
}
private child(parent: Node, name: string): Node {
const node = parent.getChildByName(name);
if (!node) throw new Error(`Missing welcome node: ${name}`);
return node;
}
private box(node: Node, x: number, y: number, width: number, height: number): void {
node.setPosition(x, y, 0);
node.setScale(1, 1, 1);
node.getComponent(UITransform)!.setContentSize(width, height);
}
private sprite(node: Node): void {
const sprite = node.getComponent(Sprite)!;
sprite.sizeMode = Sprite.SizeMode.CUSTOM;
sprite.trim = false;
}
private text(node: Node, text: string, x: number, y: number, width: number, height: number, font: number, underline = false): void {
const label = node.getComponent(Label)!;
label.overflow = Label.Overflow.SHRINK;
label.string = text;
label.fontFamily = 'Arial';
label.fontSize = font;
label.lineHeight = font + 8;
label.horizontalAlign = Label.HorizontalAlign.CENTER;
label.verticalAlign = Label.VerticalAlign.CENTER;
label.enableWrapText = true;
label.isBold = false;
label.isUnderline = underline;
label.color = new Color(250, 250, 250, 255);
this.box(node, x, y, width, height);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "c8bc8aab-88e5-478f-af07-00f32bd66a3a",
"files": [],
"subMetas": {},
"userData": {}
}
+24
View File
@@ -0,0 +1,24 @@
import { _decorator, Component, ResolutionPolicy, UITransform, view } from 'cc';
const { ccclass } = _decorator;
/** 保持完整设计画布;装饰背景等比覆盖额外区域。 / Preserve the entire design canvas and cover extra space with the decorative backdrop. */
@ccclass('WelcomeViewport')
export class WelcomeViewport extends Component {
private frameKey = '';
onEnable(): void { this.fit(); }
update(): void { this.fit(); }
private fit(): void {
const frame = view.getFrameSize();
if (frame.width <= 0 || frame.height <= 0) return;
const key = `${frame.width}:${frame.height}`;
if (key === this.frameKey) return;
this.frameKey = key;
const short = frame.height / frame.width < 1920 / 1080;
view.setDesignResolutionSize(1080, 1920, short ? ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.FIXED_WIDTH);
const visible = view.getVisibleSize();
// 主体切图保持原设计坐标,只有背景按覆盖比例放大。 / Keep foreground design coordinates and scale only the background to cover.
this.node.getComponent(UITransform)?.setContentSize(visible);
const cover = Math.max(visible.width / 1080, visible.height / 1920);
this.node.getChildByName('OrchardBackdrop')?.setScale(cover, cover, 1);
}
}
@@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "340496d0-474c-4678-9ee1-b7751a920e05",
"files": [],
"subMetas": {},
"userData": {}
}