Search code examples
javascriptarrayshtml5-canvas

Snake not moving properly for pixel Snake Game


Why isn't my snake properly moving? h is the head. The segments always seem to collapse into each other all getting set to the head coords. I thought it'd be as simple as remove from the back and add to the front but I guess not. Any help?

        this.segments.forEach(seg => s.setPixel(seg.x, seg.y, 1));

        const h = [...this.segments][0];

        h.x += this.vX;
        h.y += this.vY;

        this.segments.unshift(h);
        this.segments.pop();

Solution

  • I think maybe the problem is that you are failing to properly clone the head.

    const h = [...this.segments][0]; 
    

    The above assigns the first element in a newly created Array that still has the exact same objects inside. Try using the Object.assign() method:

            this.segments.forEach(seg => s.setPixel(seg.x, seg.y, 1));
    
            const h = Object.assign({}, this.segments[0]);
    
            h.x += this.vX;
            h.y += this.vY;
    
            this.segments.unshift(h);
            this.segments.pop();
    

    https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/#_1-using-spread https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/#_2-using-object-assign