2017-03-12 36 views
0

我在Snake和BasicEnemy之間創建了一個碰撞檢測。我創建了一個for循環來創建5個不同的敵人,但碰撞檢測不會被從for循環創建的任何敵人調用。碰撞只適用於一個BasicEnemy對象。爲什麼沒有爲陣列內的所有敵人調用碰撞函數?謝謝。爲什麼碰撞檢測不起作用? (p5 js框架工作)

Sketch.js

var snake; 
var food; 
var basicEnemy; 
var scl = 20; 
var enemies = []; 

function setup() { 
    createCanvas(600, 500); 
    snake = new Snake(); 
    basicEnemy = new BasicEnemy(); 

    //** CREATE FIVE ENEMIES ** 
    for (var i = 0; i < 5; i++) { 
    enemies[i] = new BasicEnemy(); 
    } 
} 

    // **FUNCTION WHEN SNAKE HITS ENEMY** 
    function collision() { 
    console.log("hit!"); 
    } 

    function draw() { 
    background(51); 

    //Draw snake 
    snake.update(); 
    snake.show(); 

    //Draw basicEnemy 
    basicEnemy.update(); 
    basicEnemy.show(); 

    //** LOOP THROUGH ENEMIES AND UPDATE AND SHOW ** 
    for (var i = 0; i < enemies.length; i++) { 
    enemies[i].show(); 
    enemies[i].update(); 

    if (enemies[i].hits(snake)) { 
     collision(); 
    } 
    } 
} 

    function keyPressed() { 
if (keyCode === UP_ARROW){ 
    snake.dir(0, -1); 
} else if (keyCode === DOWN_ARROW) { 
    snake.dir(0, 1); 
} else if (keyCode === LEFT_ARROW) { 
    snake.dir(-1 , 0); 
} else if (keyCode === RIGHT_ARROW) { 
    snake.dir(1 , 0); 
} 
} 

BasicEnemy.js

function BasicEnemy() { 
    this.x = random(700); 
    this.y = random(700); 
    this.velX = 15; 
    this.velY = 15; 
} 

//** FUNCTION TO CHECK IF ENEMY AND SNAKE ARE IN THE SAME LOCATION ** 
this.hits = function (pos) { 
    var = d = dist(this.x, this.y, pos.x, pos.y); 
    if(d < 1) { 
    return true; 
    } else { 
    return false; 
    } 
} 

this.show = function() { 
    fill(255, 0, 100); 
    rect(this.x, this.y, scl, scl); 
} 

Snake.js

function Snake() { 
    this.x = 0; 
    this.y = 0; 
    this.xspeed = 1; 
    this.yspeed = 0; 

    this.update = function() { 
    this.x = this.x + this.xspeed * scl; 
    this.y = this.y + this.yspeed * scl; 

    this.x = constrain(this.x, 0, width - scl); 
    this.y = constrain(this.y, 0, height - scl); 
    } 

    this.show = function() { 
    fill(255); 
    rect(this.x, this.y, scl, scl); 
    } 

    this.dir = function (x , y) { 
    this.xspeed = x; 
    this.yspeed = y; 
} 
} 
+0

爲什麼不使用'return d <1;'而不是2 ifs –

+0

謝謝,我會改變它。 – Sean

+0

將來請發佈[mcve]而不是整個項目。 –

回答

0

因爲你基本上檢查的左上角角之間的距離蛇和敵人,如果它們完全重疊,這隻會返回真實。

使用的AABB碰撞檢測,而不是:

return this.x + scl >= pos.x && this.x <= pos.x + scl && this.y + scl >= pos.y && this.y <= pos.y + scl; 

這返回true,如果第一個矩形包含第二矩形。

MDN says

之一簡單的形式碰撞檢測的是矩形兩者之間是軸線對準 - 這意味着不進行旋轉。該算法通過確保矩形的四條邊之間沒有間隙來工作。任何差距意味着不存在碰撞。

+0

這是正確的答案,但如果你能解釋爲什麼這段代碼有效,那將是非常好的。 –

+0

@Kevin能爲你工作嗎? –

+0

我想把你在貼子裏面發佈的代碼函數? – Sean