2016-12-11 3 views
3

Вот JavaScript для ловушки, которую я делаю. Некоторый из кода был дан, поэтому я совершенно не понимаю, как делать определенные вещи. Прямо сейчас, у меня есть разные объекты факера, которые в основном представляют собой красные прямоугольники, которые различаются по высоте и ширине. То, что я пытаюсь сделать, - это сделать так, чтобы объекты фаллера случайным образом распределялись между красным и синим (синее отображалось меньше), но я очень смущен, как это сделать. Я попытался сделать так, чтобы цвета, добавленные в game.fillstyle, были рандомизированы ранее, но это, похоже, не работает. Любая помощь или совет очень ценится - не обязательно быть ответом. Я просто хочу понять это.Добавление падающих предметов разного цвета

Также, если я должен поместить весь код, пожалуйста, дайте мне знать.

Вот JSfiddle: https://jsfiddle.net/ianlizzo/4dLr48v0/7/#&togetherjs=irGLk3uxOE

(() => { 

let canvas = document.getElementById("game"); 
let game = canvas.getContext("2d"); 
let lastTimestamp = 0; 

const FRAME_RATE = 60; 
const FRAME_DURATION = 1000/FRAME_RATE; 


let fallers = []; 
let score = 0; 


let colourValues = ["red", "blue"] 
colourValues = { 
    red: "#ff0000", 
    blue: "#0000ff" 
}; 

let colour = colourValues[Math.floor(Math.random()*colourValues.length)]; 

//ignore 
//let scoreCount = document.getElementById("scoreCount”); 

let showScore = function(){ 
    scoreCount.innerHTML = "Your score is " + score; 
}; 


let addScore = function(pointValue){ 
    score += pointValue; 
    showScore(); 
}; 

let fallerIn = function(inside){ 
    inside.captured = true; 
    addScore(inside.pointValue); 
}; 

const DEFAULT_DESCENT = 0.0001; // This is per millisecond. 
let Faller = function (x, y, width, height, dx = 0, dy = 0, ax = 0, ay = DEFAULT_DESCENT) { 
    this.x = x; 
    this.y = y; 
    this.width = width; 
    this.height = height; 

    this.captured = false; 
    this.pointValue = 5; 
    this.colour; 

    // Velocity. 
    this.dx = dx; 
    this.dy = dy; 

    // Acceleration. 
    this.ax = ax; 
    this.ay = ay; 
}; 

Faller.prototype.draw = function() { 
    game.fillStyle = colour; 
    game.fillRect(this.x, this.y, this.width, this.height); 
}; 

Faller.prototype.move = function (millisecondsElapsed) { 
    this.x += this.dx * millisecondsElapsed; 
    this.y += this.dy * millisecondsElapsed; 

    this.dx += this.ax * millisecondsElapsed; 
    this.dy += this.ay * millisecondsElapsed; 
}; 


const DEFAULT_PLAYER_WIDTH = 65; 
const DEFAULT_PLAYER_HEIGHT = 45; 
const DEFAULT_PLAYER_Y = canvas.height - DEFAULT_PLAYER_HEIGHT; 
let Player = function (x, y = DEFAULT_PLAYER_Y, width = DEFAULT_PLAYER_WIDTH, height = DEFAULT_PLAYER_HEIGHT) { 
    this.x = x; 
    this.y = y; 
    this.width = width; 
    this.height = height; 
}; 

Player.prototype.draw = function() { 
    let grd = game.createLinearGradient(0, 200, 200, 0); 
    grd.addColorStop(0, "black"); 
    grd.addColorStop(0.5, "red"); 
    grd.addColorStop(1, "white"); 
    game.fillStyle = grd; 
    game.fillRect(this.x, this.y, this.width, this.height); 
    game.fill(); 
}; 

let player = new Player(canvas.width/2); 

let draw = (millisecondsElapsed) => { 
    game.clearRect(0, 0, canvas.width, canvas.height); 

    fallers.forEach((faller) => { 
     faller.draw(); 
     faller.move(millisecondsElapsed); 
     if (!(faller.captured)&& 
      faller.y + faller.height > canvas.height && 
      faller.x + faller.width < player.x + player.width && 
      faller.x > player.x){ 
      fallerIn(faller); 
      } 
    }); 

    player.draw(); 

    fallers = fallers.filter((faller) => { 
     return faller.y < canvas.height; 
    }); 

}; 

const MIN_WIDTH = 10; 
const WIDTH_RANGE = 20; 
const MIN_HEIGHT = 10; 
const HEIGHT_RANGE = 20; 
const MILLISECONDS_BETWEEN_FALLERS = 750; 

let fallerGenerator; 
let startFallerGenerator =() => { 
    fallerGenerator = setInterval(() => { 

     let fallerWidth = Math.floor(Math.random() * WIDTH_RANGE) + MIN_WIDTH; 
     fallers.push(new Faller(
      Math.floor(Math.random() * (canvas.width - fallerWidth)), 0, 
      fallerWidth, Math.floor(Math.random() * HEIGHT_RANGE) + MIN_HEIGHT 
     )); 
    }, MILLISECONDS_BETWEEN_FALLERS); 
}; 

let stopFallerGenerator =() => clearInterval(fallerGenerator); 

let setPlayerPositionBasedOnMouse = (event) => { 
    player.x = event.clientX/document.body.clientWidth * canvas.width; 
}; 

document.body.addEventListener("mouseenter", setPlayerPositionBasedOnMouse); 
document.body.addEventListener("mousemove", setPlayerPositionBasedOnMouse); 

let running = false; 
let nextFrame = (timestamp) => { 
    if (!lastTimestamp) { 
     lastTimestamp = timestamp; 
    } 

    if (timestamp - lastTimestamp < FRAME_DURATION) { 
     if (running) { 
      window.requestAnimationFrame(nextFrame); 
     } 

     return; 
    } 

    draw(timestamp - lastTimestamp); 

    lastTimestamp = timestamp; 
    if (running) { 
     window.requestAnimationFrame(nextFrame); 
    } 
}; 

document.getElementById("start-button").addEventListener("click",() => { 
    running = true; 
    lastTimestamp = 0; 
    startFallerGenerator(); 
    window.requestAnimationFrame(nextFrame); 
}); 

document.getElementById("stop-button").addEventListener("click",() => { 
    stopFallerGenerator(); 
    running = false; 
}); 
})(); 
+0

Может быть так: 'this.colour = цвет,' в файле 'Фаллер = function' – LGSon

+0

Если нет, то разместив рабочий фрагмент кода поможет понять это – LGSon

ответ

1
let colourValues = ["red", "blue"] 
/* colourValues.length will be undefined for object. 
    colourValues = { 
    red: "#ff0000", 
    blue: "#0000ff" 
};*/ 
let colour = colourValues[Math.floor(Math.random()*colourValues.length)]; 

См this fiddle

Случайный генератор цвета должен генерировать красный цвет в течение 75%.

Faller.prototype.randomColour = function() { 
    return colourValues[Math.floor(Math.random() * colourValues.length * 0.75)]; 
    }; 

Фаллер должен использовать свой собственный цвет, чтобы заполнить

Faller.prototype.draw = function() { 
    game.fillStyle = this.colour; 
    game.fillRect(this.x, this.y, this.width, this.height); 
    }; 

, который был назначен в Faller конструктору.

this.colour = this.randomColour(); 

Я не мог понять, как установить ES6 в jsFiddle. Так что это будет сделано в ES5

+0

Спасибо! Это очень помогает. – Ian