0
# Game Objects
1
2
Game Objects are the visual and interactive elements that make up your game. Phaser provides an extensive collection of built-in game objects, from simple sprites to complex particle systems.
3
4
## Core Game Objects
5
6
### Sprite
7
Dynamic textured objects with animation and physics support.
8
9
```javascript { .api }
10
// Basic sprite creation
11
const sprite = scene.add.sprite(x, y, 'texture', frame);
12
13
// With physics
14
const physicsSprite = scene.physics.add.sprite(x, y, 'texture');
15
16
// Animation support
17
sprite.play('walkAnimation');
18
sprite.setFrame(frameIndex);
19
20
// Transform properties
21
sprite.setPosition(x, y);
22
sprite.setScale(scaleX, scaleY);
23
sprite.setRotation(radians);
24
sprite.setOrigin(originX, originY);
25
26
// Visual properties
27
sprite.setTint(0xff0000);
28
sprite.setAlpha(0.5);
29
sprite.setVisible(false);
30
sprite.setDepth(10);
31
```
32
33
**Key Methods:**
34
- `setTexture(key, frame)` - Change texture
35
- `setFrame(frame)` - Change animation frame
36
- `play(animKey, ignoreIfPlaying, startFrame)` - Play animation
37
- `setInteractive()` - Enable input events
38
39
### Image
40
Static textured display objects (no animation support).
41
42
```javascript { .api }
43
// Basic image creation
44
const image = scene.add.image(x, y, 'texture');
45
46
// Chaining methods
47
const logo = scene.add.image(400, 300, 'logo')
48
.setOrigin(0.5)
49
.setScale(2)
50
.setTint(0x00ff00);
51
52
// Load from URL at runtime
53
scene.load.image('runtime', 'https://example.com/image.png');
54
scene.load.once('complete', () => {
55
scene.add.image(100, 100, 'runtime');
56
});
57
```
58
59
**Key Methods:**
60
- `setTexture(key, frame)` - Change texture
61
- `setCrop(x, y, width, height)` - Crop image area
62
63
### Text
64
Bitmap and web font text rendering.
65
66
```javascript { .api }
67
// Basic text
68
const text = scene.add.text(x, y, 'Hello World', {
69
fontFamily: 'Arial',
70
fontSize: '32px',
71
fill: '#ffffff'
72
});
73
74
// Advanced styling
75
const styledText = scene.add.text(100, 100, 'Styled Text', {
76
fontFamily: 'Georgia, serif',
77
fontSize: '24px',
78
fill: '#ff0000',
79
stroke: '#000000',
80
strokeThickness: 4,
81
align: 'center',
82
backgroundColor: '#ffffff',
83
padding: { x: 10, y: 5 },
84
shadow: {
85
offsetX: 2,
86
offsetY: 2,
87
color: '#000000',
88
blur: 2,
89
fill: true
90
}
91
});
92
93
// Dynamic text updates
94
text.setText('New Content');
95
text.setStyle({ fontSize: '48px', fill: '#00ff00' });
96
97
// Multiline text
98
const multiline = scene.add.text(50, 50, 'Line 1\nLine 2\nLine 3', {
99
fontSize: '20px',
100
align: 'left',
101
lineSpacing: 10
102
});
103
104
// Word wrapping
105
const wrapped = scene.add.text(10, 10, 'This is a very long text that will wrap', {
106
fontSize: '16px',
107
wordWrap: { width: 300, useAdvancedWrap: true }
108
});
109
```
110
111
**Key Methods:**
112
- `setText(text)` - Update text content
113
- `setStyle(style)` - Update text style
114
- `setWordWrapWidth(width)` - Set wrap width
115
116
### BitmapText
117
High-performance text using bitmap fonts.
118
119
```javascript { .api }
120
// Load bitmap font
121
scene.load.bitmapFont('pixelFont', 'assets/fonts/pixel.png', 'assets/fonts/pixel.xml');
122
123
// Create bitmap text
124
const bitmapText = scene.add.bitmapText(x, y, 'pixelFont', 'Bitmap Text');
125
126
// Dynamic bitmap text with effects
127
const dynamicText = scene.add.dynamicBitmapText(x, y, 'pixelFont', 'Dynamic Text')
128
.setScale(2)
129
.setTint(0xff0000);
130
131
// Letter spacing and alignment
132
bitmapText.setLetterSpacing(10);
133
bitmapText.setCenterAlign();
134
```
135
136
**Key Methods:**
137
- `setText(text)` - Update text
138
- `setFont(font)` - Change font
139
- `setLetterSpacing(spacing)` - Adjust spacing
140
141
### Graphics
142
Vector graphics drawing and shapes.
143
144
```javascript { .api }
145
// Create graphics object
146
const graphics = scene.add.graphics();
147
148
// Drawing shapes
149
graphics.fillStyle(0xff0000);
150
graphics.fillRect(50, 50, 100, 100);
151
152
graphics.lineStyle(4, 0x00ff00);
153
graphics.strokeRect(200, 50, 100, 100);
154
155
// Complex drawing
156
graphics.clear();
157
graphics.fillStyle(0x0000ff, 0.8);
158
graphics.beginPath();
159
graphics.moveTo(100, 100);
160
graphics.lineTo(200, 150);
161
graphics.lineTo(50, 200);
162
graphics.closePath();
163
graphics.fillPath();
164
165
// Circles and ellipses
166
graphics.fillCircle(300, 300, 50);
167
graphics.strokeEllipse(400, 300, 60, 40);
168
169
// Gradients (WebGL only)
170
graphics.fillGradientStyle(0xff0000, 0x0000ff, 0x00ff00, 0xffff00, 1);
171
graphics.fillRect(0, 0, 100, 100);
172
173
// Line styles
174
graphics.lineStyle(8, 0xffffff, 1);
175
graphics.lineBetween(0, 0, 400, 300);
176
```
177
178
**Key Methods:**
179
- `clear()` - Clear all graphics
180
- `fillStyle(color, alpha)` - Set fill style
181
- `lineStyle(width, color, alpha)` - Set line style
182
- `beginPath()` / `closePath()` - Path drawing
183
184
### Container
185
Group and transform multiple game objects together.
186
187
```javascript { .api }
188
// Create container
189
const container = scene.add.container(x, y);
190
191
// Add children
192
const sprite1 = scene.add.sprite(0, 0, 'texture1');
193
const sprite2 = scene.add.sprite(50, 50, 'texture2');
194
container.add([sprite1, sprite2]);
195
196
// Container transforms affect all children
197
container.setPosition(200, 200);
198
container.setScale(1.5);
199
container.setRotation(Phaser.Math.DegToRad(45));
200
201
// Individual child access
202
const child = container.getAt(0);
203
container.bringToTop(sprite2);
204
container.remove(sprite1);
205
206
// Batch operations
207
container.setAlpha(0.5); // Affects all children
208
container.setVisible(false);
209
210
// Local coordinates
211
const localX = container.x + sprite1.x;
212
const localY = container.y + sprite1.y;
213
```
214
215
**Key Methods:**
216
- `add(child)` - Add child object
217
- `remove(child)` - Remove child
218
- `removeAll()` - Remove all children
219
- `getAt(index)` - Get child by index
220
221
## Shape Objects
222
223
### Rectangle
224
Vector rectangle shapes.
225
226
```javascript { .api }
227
// Basic rectangle
228
const rect = scene.add.rectangle(x, y, width, height, fillColor);
229
230
// Styled rectangle
231
const styledRect = scene.add.rectangle(200, 200, 100, 50, 0xff0000)
232
.setStrokeStyle(4, 0x00ff00)
233
.setAlpha(0.8);
234
235
// Interactive rectangle
236
rect.setInteractive();
237
rect.on('pointerdown', () => {
238
rect.setFillStyle(Phaser.Utils.Array.GetRandom([0xff0000, 0x00ff00, 0x0000ff]));
239
});
240
```
241
242
### Circle/Arc
243
Circular and arc shapes.
244
245
```javascript { .api }
246
// Full circle
247
const circle = scene.add.circle(x, y, radius, fillColor);
248
249
// Arc segment
250
const arc = scene.add.arc(x, y, radius, startAngle, endAngle, anticlockwise, fillColor);
251
252
// Pie slice
253
const pie = scene.add.arc(200, 200, 80, 0, Phaser.Math.DegToRad(120), false, 0xff0000)
254
.setStrokeStyle(3, 0x000000);
255
256
// Dynamic arc
257
arc.startAngle = Phaser.Math.DegToRad(45);
258
arc.endAngle = Phaser.Math.DegToRad(270);
259
```
260
261
### Ellipse
262
Elliptical shapes.
263
264
```javascript { .api }
265
// Basic ellipse
266
const ellipse = scene.add.ellipse(x, y, width, height, fillColor);
267
268
// Styled ellipse with stroke
269
const styledEllipse = scene.add.ellipse(300, 200, 120, 80, 0x00ff00)
270
.setStrokeStyle(2, 0x0000ff);
271
```
272
273
### Line
274
Vector lines and polylines.
275
276
```javascript { .api }
277
// Single line
278
const line = scene.add.line(x, y, x1, y1, x2, y2, strokeColor);
279
280
// Styled line
281
const styledLine = scene.add.line(400, 300, 0, 0, 100, 100, 0xff0000)
282
.setLineWidth(5);
283
284
// Update line endpoints
285
line.setTo(newX1, newY1, newX2, newY2);
286
```
287
288
### Polygon
289
Complex polygon shapes.
290
291
```javascript { .api }
292
// Triangle
293
const triangle = scene.add.triangle(x, y, x1, y1, x2, y2, x3, y3, fillColor);
294
295
// Star shape
296
const star = scene.add.star(x, y, points, innerRadius, outerRadius, fillColor);
297
298
// Custom polygon from points
299
const polygon = scene.add.polygon(x, y, [
300
0, 50, // Point 1
301
50, 0, // Point 2
302
100, 50, // Point 3
303
50, 100 // Point 4
304
], fillColor);
305
```
306
307
### Grid
308
Grid pattern shapes.
309
310
```javascript { .api }
311
// Basic grid
312
const grid = scene.add.grid(x, y, width, height, cellWidth, cellHeight, fillColor);
313
314
// Styled grid with alternating colors
315
const chessboard = scene.add.grid(400, 300, 320, 320, 40, 40, 0xffffff, 1, 0x000000, 1);
316
317
// Grid with stroke
318
grid.setStrokeStyle(1, 0x000000);
319
```
320
321
## Advanced Game Objects
322
323
### TileSprite
324
Repeating tiled textures.
325
326
```javascript { .api }
327
// Basic tile sprite
328
const tileSprite = scene.add.tileSprite(x, y, width, height, 'texture');
329
330
// Scrolling background
331
const scrollingBg = scene.add.tileSprite(0, 0, 800, 600, 'background')
332
.setOrigin(0);
333
334
// Animate tiling
335
scene.tweens.add({
336
targets: scrollingBg,
337
tilePositionX: 500,
338
duration: 3000,
339
repeat: -1
340
});
341
342
// Update tile position manually
343
tileSprite.tilePositionX += 1;
344
tileSprite.tilePositionY += 0.5;
345
```
346
347
### Video
348
Video playback objects.
349
350
```javascript { .api }
351
// Load video
352
scene.load.video('intro', 'assets/intro.mp4');
353
354
// Create video object
355
const video = scene.add.video(400, 300, 'intro');
356
357
// Playback control
358
video.play();
359
video.pause();
360
video.stop();
361
video.setLoop(true);
362
363
// Video events
364
video.on('play', () => console.log('Video started'));
365
video.on('complete', () => console.log('Video finished'));
366
367
// Video as texture
368
const videoSprite = scene.add.sprite(400, 300, video);
369
```
370
371
### Zone
372
Invisible interactive areas.
373
374
```javascript { .api }
375
// Create invisible zone
376
const zone = scene.add.zone(x, y, width, height);
377
378
// Make zone interactive
379
zone.setInteractive();
380
zone.on('pointerenter', () => {
381
console.log('Entered zone');
382
});
383
384
// Drop zone
385
zone.setRectangleDropZone(width, height);
386
zone.on('drop', (pointer, gameObject) => {
387
gameObject.x = zone.x;
388
gameObject.y = zone.y;
389
});
390
391
// Circular zone
392
const circularZone = scene.add.zone(300, 300, 100, 100)
393
.setCircleDropZone(50);
394
```
395
396
### RenderTexture
397
Dynamic textures for drawing operations.
398
399
```javascript { .api }
400
// Create render texture
401
const renderTexture = scene.add.renderTexture(x, y, width, height);
402
403
// Draw objects to texture
404
renderTexture.draw(sprite, 100, 100);
405
renderTexture.drawFrame('atlas', 'frame', 0, 0);
406
407
// Render texture operations
408
renderTexture.clear();
409
renderTexture.fill(0xff0000);
410
renderTexture.stamp('texture', 50, 50);
411
412
// Use render texture
413
const resultSprite = scene.add.sprite(400, 300, renderTexture.texture);
414
415
// Save render texture
416
renderTexture.snapshot((image) => {
417
// Use image data
418
});
419
```
420
421
### Blitter
422
High-performance sprite batching system.
423
424
```javascript { .api }
425
// Create blitter
426
const blitter = scene.add.blitter(0, 0, 'texture');
427
428
// Add bob objects (lightweight sprites)
429
const bob1 = blitter.create(100, 100);
430
const bob2 = blitter.create(200, 200, 'frame2');
431
432
// Bob properties
433
bob1.setPosition(150, 150);
434
bob1.setScale(2);
435
bob1.setAlpha(0.5);
436
bob1.setTint(0xff0000);
437
438
// Batch operations for performance
439
for (let i = 0; i < 1000; i++) {
440
blitter.create(
441
Phaser.Math.Between(0, 800),
442
Phaser.Math.Between(0, 600)
443
);
444
}
445
```
446
447
## WebGL-Specific Objects
448
449
### Shader
450
Custom WebGL shaders.
451
452
```javascript { .api }
453
// Load shader
454
scene.load.glsl('plasma', 'shaders/plasma.frag');
455
456
// Create shader object
457
const shader = scene.add.shader('plasma', x, y, width, height);
458
459
// Shader uniforms
460
shader.setUniform('time.value', 0);
461
shader.setUniform('resolution.value.x', width);
462
shader.setUniform('resolution.value.y', height);
463
464
// Animate shader
465
scene.tweens.add({
466
targets: shader,
467
'uniforms.time.value': 10,
468
duration: 5000,
469
repeat: -1,
470
yoyo: true
471
});
472
```
473
474
### Mesh
475
3D mesh objects.
476
477
```javascript { .api }
478
// Create mesh
479
const mesh = scene.add.mesh(x, y, 'texture');
480
481
// Set vertices (quad example)
482
mesh.addVertices([
483
-50, -50, 0, 0, // Top-left
484
50, -50, 1, 0, // Top-right
485
-50, 50, 0, 1, // Bottom-left
486
50, 50, 1, 1 // Bottom-right
487
], [0, 1, 2, 2, 1, 3]);
488
489
// 3D rotation
490
mesh.rotateX += 0.01;
491
mesh.rotateY += 0.01;
492
493
// Perspective
494
mesh.setPerspective(width, height, 45);
495
```
496
497
### PointLight
498
2D point lights for lighting effects.
499
500
```javascript { .api }
501
// Enable lighting on scene
502
scene.lights.enable();
503
scene.lights.setAmbientColor(0x404040);
504
505
// Create point light
506
const light = scene.add.pointlight(x, y, color, radius, intensity);
507
508
// Light properties
509
light.color.setTo(255, 100, 100);
510
light.radius = 200;
511
light.intensity = 0.8;
512
513
// Animated light
514
scene.tweens.add({
515
targets: light,
516
radius: 300,
517
intensity: 1.2,
518
duration: 2000,
519
yoyo: true,
520
repeat: -1
521
});
522
```
523
524
## Particle Systems
525
526
### Particle Emitters
527
Complex particle effects.
528
529
```javascript { .api }
530
// Create emitter
531
const particles = scene.add.particles(x, y, 'texture', {
532
speed: { min: 100, max: 200 },
533
scale: { start: 0.5, end: 0 },
534
lifespan: 300,
535
quantity: 2
536
});
537
538
// Advanced particle configuration
539
const explosion = scene.add.particles(400, 300, 'particle', {
540
speed: { min: 150, max: 250 },
541
scale: { start: 1, end: 0.3 },
542
rotate: { min: -180, max: 180 },
543
alpha: { start: 1, end: 0 },
544
tint: [0xff0000, 0xff8800, 0xffff00],
545
lifespan: 500,
546
quantity: 50,
547
frequency: 100,
548
emitZone: {
549
type: 'edge',
550
source: new Phaser.Geom.Circle(0, 0, 50),
551
quantity: 20
552
}
553
});
554
555
// Control emission
556
particles.start();
557
particles.stop();
558
particles.explode(50); // Burst of 50 particles
559
560
// Follow target
561
particles.startFollow(player);
562
particles.stopFollow();
563
564
// Dynamic properties
565
particles.setSpeed({ min: 50, max: 150 });
566
particles.setLifespan(1000);
567
```
568
569
## Object Management
570
571
### GameObject Factory (scene.add)
572
Creates objects and adds them to display list.
573
574
```javascript { .api }
575
// Factory methods return the created object
576
const sprite = scene.add.sprite(x, y, 'texture');
577
const text = scene.add.text(x, y, 'Hello');
578
const group = scene.add.group();
579
580
// Chaining for configuration
581
const configuredSprite = scene.add.sprite(100, 100, 'player')
582
.setScale(2)
583
.setTint(0xff0000)
584
.setInteractive();
585
```
586
587
### GameObject Creator (scene.make)
588
Creates objects without adding to display list.
589
590
```javascript { .api }
591
// Creator methods for manual management
592
const sprite = scene.make.sprite({
593
x: 100,
594
y: 100,
595
key: 'texture',
596
add: false // Don't add to display list
597
});
598
599
// Add to display list manually
600
scene.add.existing(sprite);
601
602
// Or add to container
603
container.add(sprite);
604
```
605
606
### Groups
607
Collections of game objects.
608
609
```javascript { .api }
610
// Create group
611
const enemies = scene.add.group();
612
613
// Add objects to group
614
enemies.add(enemy1);
615
enemies.add(enemy2);
616
enemies.addMultiple([enemy3, enemy4, enemy5]);
617
618
// Create objects in group
619
enemies.create(100, 100, 'enemy');
620
enemies.createMultiple({
621
key: 'enemy',
622
quantity: 10,
623
setXY: { x: 100, y: 100, stepX: 50 }
624
});
625
626
// Group operations
627
enemies.setAlpha(0.5); // Apply to all children
628
enemies.setVelocityX(100); // If physics enabled
629
630
// Group callbacks
631
enemies.children.iterate((enemy) => {
632
enemy.setTint(0xff0000);
633
});
634
635
// Physics groups
636
const physicsGroup = scene.physics.add.group();
637
```
638
639
### Layer
640
Display layers for z-index management.
641
642
```javascript { .api }
643
// Create layer
644
const backgroundLayer = scene.add.layer();
645
const gameLayer = scene.add.layer();
646
const uiLayer = scene.add.layer();
647
648
// Add objects to layers
649
backgroundLayer.add(background);
650
gameLayer.add([player, enemies]);
651
uiLayer.add([healthBar, score]);
652
653
// Layer properties
654
backgroundLayer.setAlpha(0.8);
655
gameLayer.setVisible(false);
656
uiLayer.setScrollFactor(0); // UI stays fixed to camera
657
```
658
659
## Component System
660
661
Game objects use a component-based architecture for shared functionality:
662
663
### Transform Components
664
```javascript { .api }
665
// Position
666
gameObject.x = 100;
667
gameObject.y = 200;
668
gameObject.setPosition(x, y);
669
670
// Scale
671
gameObject.scaleX = 2;
672
gameObject.scaleY = 0.5;
673
gameObject.setScale(x, y);
674
675
// Rotation
676
gameObject.rotation = Phaser.Math.DegToRad(45);
677
gameObject.setRotation(radians);
678
679
// Origin
680
gameObject.originX = 0.5;
681
gameObject.originY = 0;
682
gameObject.setOrigin(x, y);
683
```
684
685
### Visual Components
686
```javascript { .api }
687
// Alpha
688
gameObject.alpha = 0.5;
689
gameObject.setAlpha(0.8);
690
691
// Tint
692
gameObject.tint = 0xff0000;
693
gameObject.setTint(0x00ff00);
694
695
// Blend mode
696
gameObject.blendMode = Phaser.BlendModes.ADD;
697
gameObject.setBlendMode(Phaser.BlendModes.MULTIPLY);
698
699
// Depth
700
gameObject.depth = 10;
701
gameObject.setDepth(5);
702
703
// Visibility
704
gameObject.visible = false;
705
gameObject.setVisible(true);
706
```
707
708
### Input Components
709
```javascript { .api }
710
// Make interactive
711
gameObject.setInteractive();
712
713
// Custom hit areas
714
gameObject.setInteractive(new Phaser.Geom.Rectangle(0, 0, 100, 50));
715
gameObject.setInteractive(new Phaser.Geom.Circle(25, 25, 25));
716
717
// Input events
718
gameObject.on('pointerdown', handleClick);
719
gameObject.on('pointerover', handleHover);
720
gameObject.on('drag', handleDrag);
721
722
// Enable dragging
723
gameObject.setInteractive({ draggable: true });
724
```
725
726
This comprehensive game object system provides the foundation for creating rich, interactive games with Phaser's powerful rendering and component architecture.