or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

actions.mdanimation.mdaudio.mdcameras.mddata-management.mdevents.mdgame-objects.mdindex.mdinput.mdloading.mdmath-geometry.mdphysics.mdrendering.mdscenes.mdtweens.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Phaser provides an extensive collection of utility functions organized into functional modules for common programming tasks, device detection, array manipulation, object operations, and mathematical calculations.

3

4

## Capabilities

5

6

### Array Utilities

7

8

Comprehensive array manipulation functions for game object management:

9

10

```javascript { .api }

11

// Adding elements

12

Phaser.Utils.Array.Add(array, item, limit, callback, context); // Add item with optional limit

13

Phaser.Utils.Array.AddAt(array, item, index, limit, callback, context); // Add at specific index

14

15

// Removing elements

16

Phaser.Utils.Array.Remove(array, item, callback, context); // Remove first occurrence

17

Phaser.Utils.Array.RemoveAt(array, index, callback, context); // Remove at index

18

Phaser.Utils.Array.RemoveBetween(array, startIndex, endIndex, callback); // Remove range

19

Phaser.Utils.Array.RemoveRandomElement(array, start, length); // Remove random element

20

21

// Position manipulation

22

Phaser.Utils.Array.BringToTop(array, item); // Move to end of array

23

Phaser.Utils.Array.SendToBack(array, item); // Move to start of array

24

Phaser.Utils.Array.MoveUp(array, item); // Move one position up

25

Phaser.Utils.Array.MoveDown(array, item); // Move one position down

26

Phaser.Utils.Array.MoveTo(array, item, index); // Move to specific index

27

28

// Searching and selection

29

Phaser.Utils.Array.GetFirst(array, property, value, startIndex, endIndex); // Find first match

30

Phaser.Utils.Array.GetAll(array, property, value, startIndex, endIndex); // Find all matches

31

Phaser.Utils.Array.GetRandom(array, startIndex, length); // Get random element

32

Phaser.Utils.Array.GetRandomElement(array, start, length); // Get random element (alias)

33

34

// Array operations

35

Phaser.Utils.Array.Shuffle(array); // Randomize order

36

Phaser.Utils.Array.Replace(array, oldChild, newChild); // Replace element

37

Phaser.Utils.Array.RotateLeft(array, total); // Rotate elements left

38

Phaser.Utils.Array.RotateRight(array, total); // Rotate elements right

39

40

// Numerical operations

41

Phaser.Utils.Array.NumberArray(start, end); // Create number sequence

42

Phaser.Utils.Array.NumberArrayStep(start, end, step); // Create with custom step

43

44

// Utility checks

45

Phaser.Utils.Array.FindClosestInSorted(array, value); // Binary search closest value

46

Phaser.Utils.Array.CountAllMatching(array, property, value); // Count matching elements

47

Phaser.Utils.Array.Each(array, callback, context, ...args); // Iterate with callback

48

Phaser.Utils.Array.EachInRange(array, callback, context, startIndex, endIndex); // Iterate range

49

```

50

51

### Object Utilities

52

53

Object manipulation and property access functions:

54

55

```javascript { .api }

56

// Object cloning and merging

57

const cloned = Phaser.Utils.Objects.Clone(originalObject); // Deep clone

58

const merged = Phaser.Utils.Objects.Extend(target, source1, source2); // Merge objects

59

const merged2 = Phaser.Utils.Objects.Merge(target, source); // Merge with deep copy

60

const merged3 = Phaser.Utils.Objects.MergeRight(target, source); // Merge from right

61

62

// Property access

63

const value = Phaser.Utils.Objects.GetAdvancedValue(source, 'key', defaultValue);

64

const value2 = Phaser.Utils.Objects.GetFastValue(source, 'key', defaultValue);

65

const minMax = Phaser.Utils.Objects.GetMinMaxValue(source, 'key', min, max);

66

67

// Value retrieval with fallbacks

68

const advancedValue = Phaser.Utils.Objects.GetAdvancedValue(config, 'width', 800);

69

const fastValue = Phaser.Utils.Objects.GetFastValue(settings, 'volume', 1.0);

70

71

// Property path access

72

const nestedValue = Phaser.Utils.Objects.GetValue(config, 'graphics.resolution', 1);

73

74

// Object validation

75

const hasProperty = Phaser.Utils.Objects.HasValue(object, 'property');

76

const hasAll = Phaser.Utils.Objects.HasAll(object, ['prop1', 'prop2', 'prop3']);

77

const hasAny = Phaser.Utils.Objects.HasAny(object, ['prop1', 'prop2', 'prop3']);

78

79

// Example usage

80

const gameConfig = {

81

width: 800,

82

height: 600,

83

graphics: {

84

resolution: 2,

85

antialiasing: true

86

},

87

audio: {

88

volume: 0.8,

89

enabled: true

90

}

91

};

92

93

const screenWidth = Phaser.Utils.Objects.GetValue(gameConfig, 'width', 1024);

94

const resolution = Phaser.Utils.Objects.GetValue(gameConfig, 'graphics.resolution', 1);

95

const soundVolume = Phaser.Utils.Objects.GetValue(gameConfig, 'audio.volume', 1.0);

96

```

97

98

### String Utilities

99

100

String manipulation and formatting functions:

101

102

```javascript { .api }

103

// String formatting

104

const formatted = Phaser.Utils.String.Format(template, ...args); // sprintf-style formatting

105

const padded = Phaser.Utils.String.Pad(string, length, pad); // Pad string to length

106

const reverse = Phaser.Utils.String.Reverse(string); // Reverse string

107

const uppercased = Phaser.Utils.String.UppercaseFirst(string); // Capitalize first letter

108

109

// Template processing

110

const processed = Phaser.Utils.String.Template(template, data); // Template substitution

111

112

// UUID generation

113

const uuid = Phaser.Utils.String.UUID(); // Generate UUID

114

115

// Example usage

116

const template = "Player {name} scored {score} points in level {level}";

117

const message = Phaser.Utils.String.Template(template, {

118

name: "Alice",

119

score: 1500,

120

level: 3

121

});

122

// Result: "Player Alice scored 1500 points in level 3"

123

124

const formattedScore = Phaser.Utils.String.Pad(score.toString(), 6, '0');

125

// Result: "001500" for score = 1500

126

127

const playerId = Phaser.Utils.String.UUID();

128

// Result: "a1e4f2c8-d3b7-4a5e-9f8c-2d6e7a8b9c0d"

129

```

130

131

### Device Detection

132

133

Comprehensive device and browser capability detection:

134

135

```javascript { .api }

136

// Device type detection

137

const device = scene.sys.game.device;

138

139

// Operating System

140

device.os.android // Android device

141

device.os.chromeOS // Chrome OS

142

device.os.cordova // Cordova/PhoneGap

143

device.os.crosswalk // Intel Crosswalk

144

device.os.desktop // Desktop computer

145

device.os.ejecta // Ejecta (iOS JavaScript engine)

146

device.os.electron // Electron app

147

device.os.iOS // iOS device

148

device.os.iPad // iPad specifically

149

device.os.iPhone // iPhone specifically

150

device.os.kindle // Amazon Kindle

151

device.os.linux // Linux OS

152

device.os.macOS // macOS

153

device.os.node // Node.js environment

154

device.os.nodeWebkit // Node-Webkit (NW.js)

155

device.os.webApp // Web application

156

device.os.windows // Windows OS

157

device.os.windowsPhone // Windows Phone

158

159

// Browser detection

160

device.browser.chrome // Google Chrome

161

device.browser.edge // Microsoft Edge

162

device.browser.firefox // Mozilla Firefox

163

device.browser.ie // Internet Explorer

164

device.browser.mobileSafari // Mobile Safari

165

device.browser.opera // Opera

166

device.browser.safari // Safari

167

device.browser.silk // Amazon Silk

168

device.browser.trident // Trident engine

169

170

// Input capabilities

171

device.input.keyboard // Keyboard available

172

device.input.mouse // Mouse available

173

device.input.touch // Touch input available

174

device.input.gamepad // Gamepad support

175

176

// Audio capabilities

177

device.audio.audioData // Audio Data API

178

device.audio.dolby // Dolby audio support

179

device.audio.mp3 // MP3 format support

180

device.audio.ogg // OGG format support

181

device.audio.opus // Opus format support

182

device.audio.wav // WAV format support

183

device.audio.webAudio // Web Audio API

184

device.audio.m4a // M4A format support

185

186

// Video capabilities

187

device.video.h264 // H.264 codec support

188

device.video.hls // HLS streaming support

189

device.video.mp4 // MP4 format support

190

device.video.ogg // OGG video support

191

device.video.vp9 // VP9 codec support

192

device.video.webm // WebM format support

193

194

// Canvas capabilities

195

device.canvasFeatures.supportInvertedAlpha // Inverted alpha support

196

device.canvasFeatures.supportNewBlendModes // New blend modes

197

198

// Feature detection

199

device.features.canvas // Canvas support

200

device.features.canvasText // Canvas text support

201

device.features.file // File API

202

device.features.fileSystem // File System API

203

device.features.getUserMedia // getUserMedia API

204

device.features.littleEndian // Little endian byte order

205

device.features.localStorage // Local storage support

206

device.features.pointerLock // Pointer lock API

207

device.features.support32bit // 32-bit support

208

device.features.vibration // Vibration API

209

device.features.webGL // WebGL support

210

device.features.worker // Web Workers support

211

```

212

213

### Base64 Utilities

214

215

Base64 encoding and decoding functions:

216

217

```javascript { .api }

218

// String encoding/decoding

219

const encoded = Phaser.Utils.Base64.Encode(stringData); // Encode string to base64

220

const decoded = Phaser.Utils.Base64.Decode(base64String); // Decode base64 to string

221

222

// ArrayBuffer operations

223

const encodedBuffer = Phaser.Utils.Base64.ArrayBufferToBase64(buffer); // Encode ArrayBuffer

224

const decodedBuffer = Phaser.Utils.Base64.Base64ToArrayBuffer(base64); // Decode to ArrayBuffer

225

226

// Example usage

227

const gameData = JSON.stringify({

228

level: 5,

229

score: 1500,

230

inventory: ['sword', 'potion', 'key']

231

});

232

233

const encodedSave = Phaser.Utils.Base64.Encode(gameData);

234

localStorage.setItem('gameState', encodedSave);

235

236

// Later, load the data

237

const savedData = localStorage.getItem('gameState');

238

const decodedData = Phaser.Utils.Base64.Decode(savedData);

239

const gameState = JSON.parse(decodedData);

240

```

241

242

### NOOP and NULL Utilities

243

244

Utility functions for default values and empty operations:

245

246

```javascript { .api }

247

// No-operation function

248

Phaser.Utils.NOOP(); // Function that does nothing, returns undefined

249

250

// NULL function

251

Phaser.Utils.NULL(); // Function that does nothing, returns false

252

253

// Example usage in callbacks

254

const config = {

255

onComplete: callback || Phaser.Utils.NOOP, // Use NOOP if no callback provided

256

onError: errorHandler || Phaser.Utils.NULL // Use NULL if no error handler

257

};

258

259

// Default event handlers

260

gameObject.on('complete', onComplete || Phaser.Utils.NOOP);

261

gameObject.on('error', onError || Phaser.Utils.NULL);

262

```

263

264

### Advanced Utility Patterns

265

266

```javascript { .api }

267

// Configuration management with utilities

268

class GameSettings {

269

constructor(config = {}) {

270

this.width = Phaser.Utils.Objects.GetValue(config, 'width', 800);

271

this.height = Phaser.Utils.Objects.GetValue(config, 'height', 600);

272

this.volume = Phaser.Utils.Objects.GetValue(config, 'audio.volume', 1.0);

273

this.quality = Phaser.Utils.Objects.GetValue(config, 'graphics.quality', 'medium');

274

275

// Merge default settings with user config

276

this.settings = Phaser.Utils.Objects.Merge({

277

graphics: { antialiasing: true, resolution: 1 },

278

audio: { enabled: true, volume: 1.0 },

279

controls: { keyboard: true, mouse: true }

280

}, config);

281

}

282

283

save() {

284

const data = Phaser.Utils.Base64.Encode(JSON.stringify(this.settings));

285

localStorage.setItem('gameSettings', data);

286

}

287

288

load() {

289

const saved = localStorage.getItem('gameSettings');

290

if (saved) {

291

const decoded = Phaser.Utils.Base64.Decode(saved);

292

const loadedSettings = JSON.parse(decoded);

293

this.settings = Phaser.Utils.Objects.Merge(this.settings, loadedSettings);

294

}

295

}

296

}

297

298

// Array-based game object management

299

class ObjectPool {

300

constructor() {

301

this.pool = [];

302

this.active = [];

303

}

304

305

get() {

306

let obj = Phaser.Utils.Array.RemoveRandomElement(this.pool);

307

if (!obj) {

308

obj = this.create();

309

}

310

Phaser.Utils.Array.Add(this.active, obj);

311

return obj;

312

}

313

314

release(obj) {

315

Phaser.Utils.Array.Remove(this.active, obj);

316

Phaser.Utils.Array.Add(this.pool, obj);

317

obj.reset();

318

}

319

320

create() {

321

// Override in subclass

322

return {};

323

}

324

325

shuffleActive() {

326

Phaser.Utils.Array.Shuffle(this.active);

327

}

328

329

getRandomActive() {

330

return Phaser.Utils.Array.GetRandom(this.active);

331

}

332

}

333

334

// Device-specific optimizations

335

function optimizeForDevice(scene) {

336

const device = scene.sys.game.device;

337

338

if (device.os.mobile) {

339

// Mobile optimizations

340

scene.physics.world.fps = 30; // Lower physics rate

341

scene.sound.volume = device.os.iOS ? 0.7 : 0.8; // iOS volume adjustment

342

}

343

344

if (device.browser.ie) {

345

// IE-specific fallbacks

346

scene.renderer.type = Phaser.CANVAS; // Force canvas on IE

347

}

348

349

if (!device.features.webGL) {

350

// WebGL fallback

351

console.log('WebGL not supported, using Canvas renderer');

352

scene.renderer.type = Phaser.CANVAS;

353

}

354

355

if (device.input.touch && !device.input.mouse) {

356

// Touch-only interface adjustments

357

scene.input.addPointer(2); // Support multi-touch

358

}

359

}

360

```

361

362

## Types

363

364

```javascript { .api }

365

// Array Utilities

366

namespace Phaser.Utils.Array {

367

function Add<T>(array: T[], item: T | T[], limit?: number, callback?: function, context?: any): T[];

368

function Remove<T>(array: T[], item: T, callback?: function, context?: any): T;

369

function GetRandom<T>(array: T[], startIndex?: number, length?: number): T;

370

function Shuffle<T>(array: T[]): T[];

371

// ... additional array function signatures

372

}

373

374

// Object Utilities

375

namespace Phaser.Utils.Objects {

376

function Clone(obj: object): object;

377

function Extend(target: object, ...sources: object[]): object;

378

function GetValue(source: object, key: string, defaultValue?: any): any;

379

function HasValue(source: object, key: string): boolean;

380

// ... additional object function signatures

381

}

382

383

// String Utilities

384

namespace Phaser.Utils.String {

385

function Format(string: string, ...args: any[]): string;

386

function Pad(string: string, length: number, pad?: string): string;

387

function Template(template: string, data: object): string;

388

function UUID(): string;

389

// ... additional string function signatures

390

}

391

392

// Base64 Utilities

393

namespace Phaser.Utils.Base64 {

394

function Encode(data: string): string;

395

function Decode(data: string): string;

396

function ArrayBufferToBase64(buffer: ArrayBuffer): string;

397

function Base64ToArrayBuffer(base64: string): ArrayBuffer;

398

}

399

400

// Device Detection Types

401

interface Device {

402

os: {

403

android: boolean;

404

iOS: boolean;

405

desktop: boolean;

406

// ... additional OS flags

407

};

408

browser: {

409

chrome: boolean;

410

firefox: boolean;

411

safari: boolean;

412

// ... additional browser flags

413

};

414

features: {

415

webGL: boolean;

416

canvas: boolean;

417

localStorage: boolean;

418

// ... additional feature flags

419

};

420

}

421

```