原案例:http://www.phaser.io/examples/v2/world/fixed-to-camera
效果图
首先是游戏入口index.html
这里我们使用的版本是2.6.2 ,自行到phaser官网下载,资源文件自行下载,注意路径
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>phaser.js demo</title>
<script src="../js/phaser.2.6.2.min.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script src="fixed_to_camera.js"></script>
</body>
</html>
fixed_to_camera.js,代码中有很多注释
var game = new Phaser.Game(800,600,Phaser.AUTO, 'phaser-example',
{preload:preload,create:create,update:update,render:render});
function preload() {
//设置背景颜色
game.stage.backgroundColor = '#007236';
//加载图片
game.load.image('mushroom', '../assets/sprites/mushroom2.png');
game.load.image('sonic', '../assets/sprites/sonic_havok_sanity.png');
game.load.image('phaser', '../assets/sprites/phaser1.png');
}
var cursors;
var logo1;
var logo2;
function create() {
// 设置游戏世界大小
game.world.setBounds(-1000, -1000, 2000, 2000);
for (var i = 0; i < 10; i++)
{
//game.world.randomX 获取一个小于或等于游戏世界当前宽度的随机整数
game.add.sprite(game.world.randomX,game.world.randomY , 'mushroom');
}
//创建跟随着背景移动的文字
game.add.text(0, 0, "this text scrolls\nwith the background", { font: "32px Arial", fill: "#f26c4f", align: "center" });
logo1 = game.add.sprite(0, 0, 'phaser');
//fixedToCamera 设置是否固定在相机上的一个小组使用它的XY坐标系作为相机左上角的偏移量
logo1.fixedToCamera = true;
logo1.cameraOffset.setTo(500, 100);
logo2 = game.add.sprite(0, 0, 'phaser');
logo2.fixedToCamera = true;
logo2.cameraOffset.setTo(500, 100);
//创建相对于相机位置的文字
var t = game.add.text(0, 0, "this text is fixed to the camera", { font: "32px Arial", fill: "#ffffff", align: "center" });
t.fixedToCamera = true;
t.cameraOffset.setTo(200, 500);
//创建动画
game.add.tween(
logo2.cameraOffset //对象参数
).to(
{ y: 400 },//对象参数
2000, //间隔毫秒 默认为1000
Phaser.Easing.Back.InOut,//设置缓动变化率 默认null
true,//是否自动开始 默认false
0,//多少毫秒延迟 默认0
-1,//重复次数,-1永远重复 0不重复 n>=1 重复n次 默认0
true //是否为yoyo模式,即反转,向悠悠球一样 默认false
);
// 得到键盘输入控制
//createCursorKeys 创建并返回一个包含4个热键的对象,分别为Up,Down,Left和Right。
cursors = game.input.keyboard.createCursorKeys();
}
function render() {
//debug信息
game.debug.cameraInfo(game.camera, 32, 32);
}
function update() {
if (cursors.up.isDown)
game.camera.y -= 4;
else if (cursors.down.isDown)
game.camera.y += 4;
if (cursors.left.isDown)
game.camera.x -= 4;
else if (cursors.right.isDown)
game.camera.x += 4;
}