Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              * {
    box-sizing: border-box;
}

body {
    padding: 0;
    margin: 0;
    background-color: #333;
    color: #fff;
    font-family: 'Roboto', arial;
}

canvas {
    margin: 20px auto;
    display: block;
    border: 2px solid rgba(255, 255, 255, 0.1);
    border-radius: 2px;
}

            
          
!
            
              class Arrow {
    constructor(coords, player, floor) {
        this.r = 5;
        this.player = player;
        this.floor = floor;
        // Copy the player that shot the arrow so we can start the arrow from the player's position
        let playerPos = player.pos.copy();
        this.pos = createVector(playerPos.x, playerPos.y);
        this.acc = createVector();
        this.vel = createVector();
        // Get the length of the user's dragged arrow
        this.mag =
            coords.length === 2
                ? dist(coords[0].x, coords[0].y, coords[1].x, coords[1].y)
                : 1;
        this.landed = false;
        this.intersected = false;
        this.scored = false;
    }

    update() {
        // Only apply forces to the arrow if it didn't land on something
        if (!this.landed) {
            this.vel.add(this.acc);
            this.pos.add(this.vel);
            this.acc.mult(0);
        }
    }

    // Apply the shooting force to the arrow
    shoot(f) {
        // Multiply the shooting force by the length of the user's dragged arrow
        f.mult(this.mag);
        // Limit how much force can by applied to the arrow
        f.limit(12);
        // Apply the shooting force to the arrow
        this.applyForce(f);
    }

    // Check if the arrow hits the given player
    hits(player) {
        if (
            // check x axis
            this.pos.x > player.pos.x &&
            this.pos.x < player.pos.x + player.w &&
            // check y axis
            this.pos.y > player.pos.y &&
            this.pos.y < player.pos.y + player.h
        ) {
            return true;
        }
        return false;
    }

    // General function that apply a given force to this object
    applyForce(f) {
        this.acc.add(f);
    }

    // Render the arrow to the screen
    show() {
        noStroke();
        fill(255);
        // We will paint the arrow red if it hits "intersected" with one of the players
        if (this.landed && this.intersected) fill(255, 0, 0);
        // We will reduce the alpha of the arrow if it hits the floor
        if (this.landed && !this.intersected) fill(255, 50);
        push();
        translate(this.pos.x, this.pos.y);
        // Rotate the arrow by the velocity's angle
        rotate(this.vel.heading());
        rectMode(CENTER);
        rect(0, 0, this.r * 4, this.r * 0.5);
        // The arrow's tip
        triangle(
            (this.r * 2) / 2,
            (-this.r * 2) / 2,

            (this.r * 2) / 2,
            (this.r * 2) / 2,

            this.r * 2,
            0
        );
        pop();
    }

    // Check if the arrow hits the floor
    edges(floor) {
        if (this.pos.y > height - floor.h - this.r / 2) {
            // If it does hits the floor, check it as landed
            this.landed = true;
        }
    }
}



















class Floor {
    constructor() {
        this.h = 200;
    }

    // Render the floor
    show() {
        fill(45);
        noStroke();
        rect(0, height - this.h, width * 2, height);
    }
}














class Player {
    constructor(x, y, w = 20, h = 40) {
        this.w = w;
        this.h = h;
        // We offset the player by half of his height so he can be correctly be rendered just above the floor
        this.pos = createVector(x, y - this.h / 2);
    }

    // Render the player
    show() {
        push();
        fill(255);
        rect(this.pos.x, this.pos.y, this.w, this.h);
        pop();
    }
}
















let player_one, player_two, floor;
let arrows = [];
let playerOneArrows = [];
let playerTwoArrows = [];
let arrowDraggingCoords = [];
let showArrowDragging = false;
let arrowIsReleased = false;
let playerOneTurn = true;
let delta = 0;

function setup() {
    createCanvas(411, 731);
    stroke(255);
    floor = new Floor();

    let playersOffset = 100;
    player_one = new Player(playersOffset, height - floor.h - 40 / 2);
    player_two = new Player(width + playersOffset, height - floor.h - 40 / 2);
}

function draw() {
    background(55);

    // Move the "Camera" by translating the whole scene
    translate(delta, 0);

    // Show score
    textSize(32);
    textAlign(CENTER);
    fill(255);
    noStroke();
    // Big numbers
    text(`${playerOneArrows.length}`, 50 - delta, 50);
    text(`${playerTwoArrows.length}`, width - 50 - delta, 50);
    // Players names
    textSize(13);
    text(`Player #1`, 50 - delta, 75);
    text(`Player #2`, width - 50 - delta, 75);

    // Increasing delta
    if (!playerOneTurn) {
        if (delta > -(width - 200)) {
            delta -= 10;
        }
    } else {
        if (delta < 0) {
            delta += 10;
        }
    }

    // Floor
    floor.show();

    // Player #1
    player_one.show();

    // Player #2
    player_two.show();

    // If the user is dragging the mouse we need to draw the line that represent the arrow's angle and magnitude
    if (showArrowDragging && arrowDraggingCoords.length === 2) {
        stroke(255);
        line(
            arrowDraggingCoords[0].x - delta,
            arrowDraggingCoords[0].y,
            arrowDraggingCoords[1].x - delta,
            arrowDraggingCoords[1].y
        );
    }

    // Create gravity force
    let gravity = createVector(0, 0.2);
    if (arrowIsReleased) {
        for (let i = arrows.length - 1; i >= 0; i--) {
            let arrow = arrows[i];

            if (!arrow.scored) {
                arrow.applyForce(gravity);
                arrow.update();
                arrow.edges(floor);
                arrow.show();
            }

            // If an arrow hits the opposite side
            if (arrow.hits(playerOneTurn ? player_one : player_two)) {
                arrow.intersected = true; // check this arrow as intersected so we can change its color
                arrow.landed = true; // check this arrow as landed so it can stop moving

                // If we didn't check this arrow as scored and its player two turn
                if (!playerOneTurn && !arrow.scored) {
                    playerOneArrows.push(copyInstance(arrow));
                }
                // If we didn't check this arrow as scored and its player one turn
                if (playerOneTurn && !arrow.scored) {
                    playerTwoArrows.push(copyInstance(arrow));
                }
                // check this arrow as scored so we don't count it multiple times
                arrow.scored = true;
            }
        }
    }
    // Delete the oldest arrow if there is too many arrows
    if (arrows.length > 10) {
        arrows.splice(0, 1);
    }

    // Show the scored arrows so that they don't disappear
    playerOneArrows.forEach(arrow => {
        arrow.applyForce(gravity);
        arrow.update();
        arrow.edges(floor);
        arrow.show();
    });
    playerTwoArrows.forEach(arrow => {
        arrow.applyForce(gravity);
        arrow.update();
        arrow.edges(floor);
        arrow.show();
    });
}

// Handle the arrow pull
function mousePressed() {
    showArrowDragging = true;
    arrowDraggingCoords[0] = {
        x: mouseX,
        y: mouseY
    };
}
function mouseDragged() {
    arrowDraggingCoords[1] = {
        x: mouseX,
        y: mouseY
    };
}
function mouseReleased() {
    // After the user drag and release we will create a new arrow with the dragging details
    let arrow = new Arrow(
        arrowDraggingCoords,
        playerOneTurn ? player_one : player_two,
        floor
    );
    // Pass the turn the other player
    playerOneTurn = !playerOneTurn;
    // We get the angle of the user's dragging coords
    let angle =
        arrowDraggingCoords.length === 2
            ? angleFromTwoPoints(arrowDraggingCoords[0], arrowDraggingCoords[1])
            : 0;
    // Create a Vector from this angle, this vector represent the arrow's force
    let vFromAngle = p5.Vector.fromAngle(angle);
    // Apply this force to the arrow
    arrow.shoot(vFromAngle);
    // Add this arrow to the rest of the old arrows
    arrows.push(arrow);

    // Reset the dragging values
    arrowIsReleased = true;
    arrowDraggingCoords = [];
    showArrowDragging = false;
}

function angleFromTwoPoints(p1, p2) {
    return Math.atan2(p1.y - p2.y, p1.x - p2.x);
}

function copyInstance(original) {
    var copied = Object.assign(
        Object.create(Object.getPrototypeOf(original)),
        original
    );
    return copied;
}

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console