使用Phaser尝试P2物理引擎

2015/01/23 17:14
阅读数 675

物理引擎通过为刚性物体赋予真实的物理属性的方式来计算运动、旋转和碰撞反映。本例程使用了Phaser中的P2物理引擎。在点击空白区域将创建一个箱子,点击箱子会消除它

<!doctype html>
<html>
    <head>
            <script src="phaser.min.js"></script>
            <style>
                body{margin:0}
            </style>
            <script type="text/javascript">
            window.onload = function() {
                var game = new Phaser.Game(720,480,Phaser.CANVAS,"",{preload:onPreload, create:onCreate});
                     
                // 载入箱子的皮肤
                function onPreload() {
                    game.load.image("crate", "crate.png");
                }
                 
                // 创建游戏
                function onCreate() {
                    // 添加 P2 物理引擎
                    game.physics.startSystem(Phaser.Physics.P2JS);
                    // 设置重力
                    game.physics.p2.gravity.y = 250;
                     // 添加鼠标按下或触摸事件
                    game.input.onDown.add(addRemove, this);       
                }
                 
                function addRemove(pointer){
                    // 检查刚体是否被点击
                    var bodyClicked = game.physics.p2.hitTest(pointer.position);
                    if(bodyClicked.length==0){
                        // 创建物理刚体
                        var crate = game.add.sprite(pointer.position.x, pointer.position.y, "crate");
                        game.physics.p2.enable(crate);
                    }
                    else{
                        // 销毁物理刚体及其图形
                        bodyClicked[0].parent.sprite.kill();
                    }
                }
                };
        </script>
    </head>
    <body>
    </body>
</html>


展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部