Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding falling objects with different colors

Tags:

javascript

Here is the JavaScript for a catcher game I’m making. Some of the code was given, which is why I quite fully don’t understand how to do certain things. Right now, I’m have different faller objects that are basically red rectangles that vary in height and width. What I’m trying to do is make it so that the faller objects randomize between red and blue (blue showing up less) but I’m extremely confused as how to do so. I tried making it so that the colors added to game.fillstyle were randomized prior, but that doesn’t seem to be working. Any help or advice is greatly appreciated–doesn’t have to be an answer. I’m just looking to figure this out.

Also, if I should put all of the code in please let me know.

Here is the 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;
});
})();
like image 802
Ian Avatar asked Jul 16 '26 14:07

Ian


1 Answers

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)];

See this fiddle

Random color generator should generate red for 75% times.

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

Faller should use its own color to fill

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

which was assigned in Faller constructor.

this.colour = this.randomColour();

I couldn't figure out how to set ES6 in jsFiddle. So it is done in ES5

like image 52
Sen Jacob Avatar answered Jul 19 '26 04:07

Sen Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!