使用Phaser嘗試P2物理引擎

物理引擎經過爲剛性物體賦予真實的物理屬性的方式來計算運動、旋轉和碰撞反映。本例程使用了Phaser中的P2物理引擎。在點擊空白區域將建立一個箱子,點擊箱子會消除它javascript

<!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>
相關文章
相關標籤/搜索