Search code examples
javascriptgame-physics

Agar.io clone using P5JS not ejecting (W) the right direction


I have attempted to make an agar.io clone using javaScript along with p5js. Here's the link on github for the full source of this project. Now, I've got the basic gist of the game, but now I'm trying to add an eject/split (In the game, by pressing W an ejection happens). But the ejection/w, is not working correctly— Basically, it's firing the w in the wrong direction, usually close to the blob. Here's the part for the ejection(W)'s position relative to the blob's position (the position where the W is fired, [should fire towards the direction of the mouse]):

this.update = function() {
        let newvel = createVector(mouseX-width/2, mouseY-height/2);
        newvel.setMag(speed);
        this.vel.lerp(newvel, 0.2);
        this.pos.add(this.vel);
    }
    let pos = createVector(mouseX - (this.pos.x + this.vel.x), mouseY - (this.pos.y + this.vel.y));


Don't worry about the few extra variables/uncalled functions (lerp, createVector, setMag, & add are all p5JS functions), the code is too long so I only put the part with the update function and the "setting the W's position" part of the code. "this.vel" is basically the velocity, so I included it in the W's new position, because as the blob is moving, the W might be eaten instantly. But it still fires W the wrong direction.... Really need to fix this ... I tried everything like

pos = createVector(mouseX - width/2, mouseY - height/2);

But nevertheless, it still fires the W the wrong direction. Unfortunately, I'm not really sure how to approach this the logical way :(
NOTE: I have also used the translate function to centre the blobs from initial position (0, 0)to translate(width / 2, height / 2)


Solution

  • The way you wrote it, it won't hurt to initialize the ejected blob at mouseX and mouseY with a translation of n-displacement, along with the constrain function limiting the blob's position on the current viewport of the map, subtracted by the distance between the blob and the cursor (by using the dist function). If you would like the animation process to be smoother, and slightly more accurate curvature-wise you can use the lerp function on top of it. Figuring out how to order these steps is simple. First get the regular plane coordinate working by translating before rendering, then integrating the curves using lerp to avoid omitting accuracy (after the calculations and constrains have been made).