2017-07-12 11 views
0

こんにちは私はヘビとゲームを作りました。私の蛇と揃っていないので、蛇に食べさせてもらえません。エラーメッセージもありません。私が間違っていた場所と、どうやって整列されて食べられるのかを説明してください。ここでJavaScript p5.js:Object Alignment

が私のコードです:

マイ食べ物:

function columns() 
{ 
    return floor(width/scl); 
} 

function rows() 
{ 
    return floor(height/scl); 
} 

function randomPlaceFood() 
{ 
    return createVector(floor(random(columns())), floor(random(rows()))); 
} 

function Food() 
{ 
    this.vector = randomPlaceFood().mult(scl); 

    this.x = random(0, 700); 
    this.y = random(0, 700); 

    this.updateFood = function() 
    { 
    this.vector = randomPlaceFood().mult(scl); 
    } 

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

} 

マイスネーク:

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

    this.xspeed = 0; 
    this.yspeed = 0; 

    this.updateSnake = 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.showSnake = function() 
    { 
    fill(255); 
    rect(this.x, this.y, scl, scl); 
    } 

    this.direction = function(x, y) 
    { 
    this.xspeed = x; 
    this.yspeed = y; 
    } 

    this.eatFood = function() 
    { 
    if (this.x === food.x && this.y === food.y) 
    { 
     randomPlaceFood(); 
    }else 
    { 
     randomPlaceFood(); 
    } 
    } 

    this.keyPressed = function() 
    { 
    if (keyCode === 87) 
    { 
     snake.direction(0, -1); 
    } else if (keyCode === 83) 
    { 
     snake.direction(0, 1); 
    } else if (keyCode === 68) 
    { 
     snake.direction(1, 0); 
    } else if (keyCode === 65) 
    { 
     snake.direction(-1, 0); 
    } 
    } 
} 

、メインファイル:

var snake; 

var scl = 20; 
var food; 


function setup() 
{ 
    //Sets the Canvas 
    createCanvas(700, 700); 

    //Creates a new object using the variable snake 
    snake = new Snake(); 

    food = new Food(); 

    frameRate(10); 

} 

function draw() 
{ 
    //Sets the Background, number implies the colour 
    background(40); 

    //Adds all the values set within the function to the snake 
    snake.updateSnake(); 
    snake.showSnake(); 
    snake.keyPressed(); 

    food.showFood(); 
    food.updateFood(); 

    if(snake.eatFood()) 
    { 
    randomPlaceFood(); 
    } 
} 

答えて

0

この行をチェックしてください:

if (this.x === food.x && this.y === food.y) 

ヘビが食品と完全に整列しているかどうかだけを確認しています。見つけたように、ピクセル完全精度が必要なので、これはほとんど起こりません。

代わりに、スネークが食物と衝突しているかどうかを検出する必要があります。これは、衝突検出を使用して行います。 Googleはあなたの友達ですが、2つの長方形をチェックするための一般的なアルゴリズムはこれです:

if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){ 
    //rectangles are colliding 
} 

恥知らずな自己宣伝:私はhere可能な衝突検出のチュートリアルを書きました。これはProcessing用ですが、P5.jsではすべてが同じです。