今天给大家分享一款基于html5和jquery的篮球跳动游戏。这款实例和之前分享的HTML5重力感应小球冲撞动画类似。用鼠标拖动篮球,篮球在页面上跳动,可在演示中看下效果。效果图如下:

基于html5和jquery的篮球跳动游戏-LMLPHP

在线预览   源码下载

实现的代码。

这个实例主要是js代码。js需要引用jquery和Phaser.js这两个库。页面上的js代码如下:

 (function () {
var w = window.innerWidth;
var h = window.innerHeight;
var game = new Phaser.Game(w, h, Phaser.CANVAS, '', {
preload: preload,
create: create,
update: update
});
var totalBalls = 8;
var balls, ballStartX, ballStartY, ballEndX, ballEndY;
function random(min, max) {
return game.rnd.integerInRange(min, max);
}
function preload() {
game.load.image('basketball', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/74196/basketball.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
balls = game.add.group();
for (var i = 0; i < totalBalls; i++) {
setTimeout(function () {
var ball = balls.create(random(0, game.world.width), -100, 'basketball');
game.physics.arcade.enable(ball);
ball.scale.setTo(0.2, 0.2);
ball.body.velocity.x = random(-50, 50);
ball.body.gravity.y = 1000;
ball.body.bounce.y = 0.5;
ball.body.bounce.x = 0.5;
ball.body.collideWorldBounds = true;
ball.inputEnabled = true;
ball.input.enableDrag(true);
ball.input.start(0, true);
ball.events.onDragStart.add(grab, ball);
ball.events.onDragStop.add(toss, ball);
}, 200 * i);
}
}
function update() {
for (var i = 0; i < balls.length; i++) {
var thisBall = balls.getAt(i);
var vX = thisBall.body.velocity.x;
var vY = thisBall.body.velocity.y;
if (thisBall.body.bottom === game.world.bounds.bottom) {
if (thisBall.body.velocity.x > 0) {
thisBall.body.velocity.x = vX - 1;
} else if (thisBall.body.velocity.x < 0) {
thisBall.body.velocity.x = vX + 1;
}
}
}
}
function grab() {
ballStartX = this.body.position.x;
ballStartY = this.body.position.y;
this.body.moves = false;
this.body.velocity.setTo(0, 0);
this.body.allowGravity = false;
}
function toss() {
ballEndX = this.body.position.x;
ballEndY = this.body.position.y;
this.body.moves = true;
this.body.allowGravity = true;
var vX = (ballEndX - ballStartX) * 10;
var vY = (ballEndY - ballStartY) * 10;
this.body.velocity.setTo(vX, vY);
}
} ());

via:http://www.w2bc.com/Article/14341

05-12 01:25