轻量级JavaScript游戏框架CreateJS创建精灵+P2JS物理引擎

ball

使用轻量级javascript游戏框架的弹性小球实例

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>P2 Physics World</title>
</head>
<body>
<body onload="init();">
<canvas id="gameView" width="1000" height="400"></canvas>
<script src="libs/createjs-2015.11.26.min.js"></script>
<script src="libs/p2.js"></script>
<script src="js/p2.js"></script>
</body>
</html>

JAVASCRIPT


var canvas,
    stage,
    container;

var world,
    redBall,
    ballBody

var stageHeight = 400,
    factor = 50;

var xPos = 150
var yPos = 20;

var isKeyDown = false;
var ballWShape;

function init() {

    // 一、 physics world
    world = new p2.World({
        gravity: [0, -9.82]
    });
    world.sleepMode = p2.World.ISLAND_SLEEPING;

    // 二、canvas createjs

    canvas = document.getElementById('gameView');
    stage = new createjs.Stage(canvas);
    container = new createjs.Container();
    stage.addChild(container);
    if (createjs.Touch.isSupported()){
        createjs.Touch.enable(stage); // 移动端接收mouse事件;
    }

    stage.enableMouseOver();

    // 三、create shape by createjs and and physicsworld to shape by p2.js

    redBall = createBall(xPos,yPos);  // createjs create ball;
    //关联p2.js物理引擎;
    ballBody = createBallWorld(xPos,yPos);
    ballBody.displays = [redBall];

    redBall.addEventListener('mousedown',function(e){
        stage.addEventListener('stagemousemove', function(e) {

          //  redBall.x = stage.mouseX;
          //  redBall.y = stage.mouseY;
            isKeyDown = true;
            redBall.x = e.stageX;
            redBall.y = e.stageY;
            stage.update();
        });
        stage.addEventListener('stagemouseup', function(e) {
           // stage.update();
            isKeyDown = false;
            // 清除旧的重力
            world.removeBody(ballBody);

            // 加入新的重力
            createBallWorld(e.stageX,e.stageY);
            addContactMaterial();
            e.target.removeAllEventListeners();
            stage.update();
        });
    });


    floor = createFloor();
    floorWorld = createFloorWorld();
    floorWorld.display = floor;

    // 材料比较;
    addContactMaterial();
    createjs.Ticker.framerate = 60;
    //console.log(ballBody.position[1]);
    createjs.Ticker.addEventListener("tick", tickHandler);

}

var addContactMaterial = function (){

    world.addContactMaterial(new p2.ContactMaterial(
        ballWShape.material,
        floorWShape.material,
        {   restitution: 0.5,  // < 1.0
            stiffness:Number.MAX_VALUE // extact restitution;
        }
    ));
}

var createBall = function (x,y) {

    var sprite = container.addChild(new createjs.Shape());
    sprite.graphics
        .beginFill("red").drawCircle(0, 0, 50)
        .beginFill("white").drawCircle(0, 0, 30)
        .beginFill("yellow").drawCircle(0, 0, 15);

    sprite.x = x;
    sprite.y = y;
    return sprite;
}

var createBallWorld = function (xPos,yPos) {

    var circlePosX = xPos;   //把球摆放在距离屏幕左上角为100,100px位置
    var circlePosY = yPos;
    var circleR = 50;

    var circlePosXInP2 = circlePosX / factor;
    var circlePosYInP2 = (stageHeight - circlePosY) / factor;
    var circleRInP2 = circleR / factor;

    // convert p2.js coordinate to createjs
    // no need to var ballBody in P2.js
    ballBody = new p2.Body({
        mass: 3,
        position: [circlePosXInP2, circlePosYInP2]
    });

    ballBody.damping = 0
    ballBody.angularDamping = 0;

    //半径也要转换
    ballWShape = new p2.Circle({
        radius: circleRInP2
    });
    // material 材质;
    ballWShape.material = new p2.Material();

    //将circle 加入重力世界
    ballBody.addShape(ballWShape);
    world.addBody(ballBody);
    return ballBody;

}

// 创建地面;
var createFloor = function () {

    var sprite = container.addChild(new createjs.Shape());
    sprite.graphics.beginFill("black").drawRect(0, stageHeight - 10, 1000, 10);
    return sprite;
}
// 创建地面物理世界  floor physics world;
var createFloorWorld = function () {

    floorWShape = new p2.Plane();
    floorWShape.material = new p2.Material();
    groundBody = new p2.Body({mass: 0});
    groundBody.addShape(floorWShape);
    world.addBody(groundBody);
    return groundBody;
}

var tickHandler = function tickHandler(x) {
    if (!isKeyDown) {
        world.step(1 / 20);
        redBall.x = ballBody.position[0] * factor;
        redBall.y = stageHeight - ballBody.position[1] * factor;
        stage.update();
    }
   // stage.update();
}

var $log = function (e) {
    console.log(e)
}

补充:一个比较好的话方法是:直接移动刚体(p2.js),形体(createjs)会随着刚体的位置变化而变化;



 var grayShape = container.addChild(new createjs.Shape());
    grayShape.graphics.beginFill("#f5f5f5").drawRect(0,0,1000,500);

    grayShape.addEventListener('mousedown',function(e){
        console.log((stageHeight - e.stageY) / factor);
        // ballBody.position[0] = (e.stageX / factor);
        // ballBody.position[1] = (stageHeight - e.stageY) / factor;

        // 推力
        // ballBody.force[1] += 10 * ballBody.position[1]; 

        // velocity  
        var force = p2.vec2.fromValues(100,0);
        p2.vec2.add(ballBody.force,ballBody.force,force);
        stage.update();
    })

Create.js 创建精灵:https://www.createjs.com/getting-started

P2.js 物理引擎:https://github.com/schteppe/p2.js

 

打赏

One comment

  1. 小篇补充:

    CreateJS 建立图形还有物理引擎还是比较不方便的

    个人建议 直接入手 Phaser.js 进行H5游戏的开发 *~_~*

Leave a Reply