2017-03-13 43 views
1

我正在嘗試使用matter.js來創建自上而下的級別炸彈人風格。Matter.js碰撞未檢測

現在我想要得到我的圈子,這是由箭頭鍵控制移動和碰撞到靜態廣場,但它只是通過他們。我錯誤地設置了它嗎?我已經編了三個月的編碼,所以我可能會很抱歉!

var Engine = Matter.Engine, 
    World = Matter.World, 
    Bodies = Matter.Bodies; 

var engine = Engine.create(); 
var world = engine.world; 

var player; 
var rocks = []; 
var cols = 7; 
var rows = 7; 

function setup() { 
    createCanvas(750, 750); 
    Engine.run(engine); 

    player = new Player(300, 300, 25); 

    var spacing = width/cols; 
    for (var j = 0; j < rows; j++) { 
     for (var i = 0; i < cols; i++) { 
      var r = new Rocks(i * spacing, j * spacing); 
      rocks.push(r); 
     } 
    } 
} 

function draw() { 
    background(51); 
    Engine.update(engine); 
    for (var i = 0; i < rocks.length; i++) { 
     rocks[i].show(); 
    } 
    player.show(); 
    player.move(); 
} 

function Player(x, y, r) { 
    this.body = Bodies.circle(x, y, r); 
    this.r = r; 
    World.add(world, this.body); 

    this.show = function() { 
     ellipse(x, y, this.r * 2); 
    } 

    this.move = function() { 
     if (keyIsDown(RIGHT_ARROW)) 
      x += 10; 
     if (keyIsDown(LEFT_ARROW)) 
      x -= 10; 
     if (keyIsDown(UP_ARROW)) 
      y -= 10; 
     if (keyIsDown(DOWN_ARROW)) 
      y += 10; 
     x = constrain(x, this.r, height - this.r); 
     y = constrain(y, this.r, width - this.r); 
    } 
} 

function Rocks(x, y, w, h, options) { 
    var options = { 
     isStatic: true 
    } 
    this.body = Bodies.rectangle(x, y, h, w, options); 
    this.w = w; 
    this.h = h; 
    this.size = player.r * 2; 
    World.add(world, this.body); 

    this.show = function() { 
     rect(x, y, this.size, this.size); 
    } 
} 

回答

1

我認爲問題是,你的球員是不是在相同的位置得出的物理引擎認爲它的。

在您的播放器函數初始化後x和y其餘全部需要爲this.body.position.xthis.body.position.y。否則,你正在改變畫面的位置,而不是玩家的實際位置。

我不完全確定你想讓我指出什麼,除此之外,但我想你想禁用與engine.world.gravity.y = 0引力,我試圖修復約束功能,因爲當我測試它不工作,我無法修復它,但我建議僅爲牆壁製作靜態邊界對象,而不要繪製它們。

另外,matter.js處理對象從其中心的位置。當繪製對象,你要麼必須考慮到這一點或模式切換爲ellipseMode(CENTER);,「rectMode(中心);`..等

我希望這有助於