Phaser是一门开源的HTML5游戏框架,对比CreateJs、Cocos2d、Hilo等等,其API最丰富最人性化,参考资源也更多,创建游戏、组织代码思路也非常清晰。整理一些常用的api方便查阅复习备忘。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// 创建一个游戏
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'parentId', {
preload: preload,
create: create,
update: update,
render : render
});


// 预加载中添加一个图片资源
game.load.image('phaser', 'assets/phaser.png');
// 预加载中添加一个雪碧图资源
game.load.spritesheet('player', 'assets/player.png', 32, 48);


// 设置游戏世界、镜头可视的范围
game.world.setBounds(-1000, -1000, 2000, 2000);


// 游戏开启Arcade(跟碰撞、遮罩、路径有关)系统
game.physics.startSystem(Phaser.Physics.ARCADE);

// 将arcade系统属性应用于player
game.physics.arcade.enable(player);

// player和platforms产生产生碰撞行为
game.physics.arcade.collide(player, platforms);

// 创建一个组
platforms = game.add.group();

// 向组内画布x=400,y=400处添加元素
ground = platforms.create(400, 400, 'ground');

// 使掉在ground上面的东西停止
ground.body.immovable = true;

// player与游戏世界边界产生碰撞
player.body.collideWorldBounds = true;


// 给palyer添加一个帧动画
player.animations.add('left', [0, 1, 2, 3], 10, true);

// 播放帧动画
player.animations.play('left');

// 水平位移(速度)
player.body.velocity.x = 10;

// y轴方向加速度
player.body.gravity.y = 10;


// 往游戏画布中x=100,y=100处添加名为phaser的图片对象
logo = game.add.sprite(100, 100, 'phaser');


// 游戏世界中随机x坐标,随机y坐标
game.world.randomX
game.world.randomY


// 游戏画布中x=0,y=0处添加一个文本
game.add.text(0, 0, 'this text scrolls\nwith the background', {
font: '32px Arial',
fill: '#f26c4f',
align: 'center'
})


// 设置元素fixed定位到镜头x=100,y=100处
logo.fixedToCamera = true;
logo.cameraOffset.setTo(100, 100);


// game.add.tween(target).to(
// properties,
// duration,
// ease,
// autoStart,
// delay,
// repeat,
// yoyo
// );
// yoyo表示是否反向
game.add.tween(logo.cameraOffset).to(
{ y: 400 },
2000,
Phaser.Easing.Back.InOut,
true,
0,
2000,
true
);


// 创建键盘事件对象,上键按下时,镜头上移4px
cursors = game.input.keyboard.createCursorKeys();
if (cursors.up.isDown) {
game.camera.y -= 4;
}

// 给logo添加点击事件
logo.events.onInputDown.add(func, this);


// 让镜头跟随logo走
game.camera.follow(logo);


// 当logo超出世界的边沿,将重置logo到世界另一边。
// 例如logo一直向左移,当超出世界左边界,logo将去到世界的右边界
game.world.wrap(logo, 0, true);