首页 > 解决方案 > 如何在JS中删除数组中的向量

问题描述

我目前正在尝试在 JS 中创建自己的蛇游戏,并且很难找到一个非常简单的问题的解决方案。所以如果我惹恼了某人,我想提前道歉。

我希望所说的蛇有一条不长于变量“长度”的尾巴。如果它是数组中的最后一个向量(存储尾部的位置),则应删除它 - 也就是最旧的向量。这是更新的代码:

////Snake Class//////
    function Snake() {
        var scl = 20;
        this.tail = [];
        this.length = 5;

        this.x = 0;
        this.y = cnv.height / 2;
        this.xspeed = 1;
        this.yspeed = 0;

        this.move = function (x, y) {
            this.xspeed =  x;
            this.yspeed =  y;
        }

        this.update = function () {
            this.x = this.x + this.xspeed * scl;
            this.y = this.y + this.yspeed * scl;        

            this.tail.unshift(createVector(this.x, this.y));

            if(this.tail.length > this.length) {
                this.tail.pop();
            }
        }

        this.show = function (){
            for (var i = 0; i < this.tail.length; i++) {
                rect(this.tail[i].x, this.tail[i].y, scl, scl);
            }
        }
    }


//////////Main Class///////////

function setup() {
    cnv = createCanvas(windowWidth, windowHeight);
    cnv.style('display','block');
    background(249,49,119);

    frameRate(10);
    s = new Snake();
}

function draw() {
    s.update();
    s.show();
}

function keyPressed() {
    if (keyCode == UP_ARROW) {
        console.log("UP");
        s.move(0, -1);
    }else if (keyCode == DOWN_ARROW){
        s.move(0,1);
    } else if (keyCode == LEFT_ARROW){
        s.move(-1, 0);
    }else if (keyCode == RIGHT_ARROW){
        s.move(1, 0);
    }
}

/////Html///////

<html>
    <head>
        <script 
        src="https://cdnjs.cloudflare.com
        /ajax/libs/p5.js/0.7.1/p5.min.js"> 
        </script>
        <script 
        src="https://cdnjs.cloudflare.com/ajax/
        libs/p5.js/0.7.1/addons/p5.dom.min.js"> 
        </script>
        <script 
        src="https://cdnjs.cloudflare.com/ajax/
        libs/p5.js/0.7.1/addons/p5.sound.min.js"></script>

   <link rel = "stylesheet" href = "style.css" type = "text/css">
   </head>
   <body>
        <script src = "Main.js"></script>
        <script src = "Snake.js"></script>
    </body>
    </html>


///CSS///
html, body {
    background-color: #919191;

    height: 100%;
}

body {
    margin: 0;
    display: flex;

    /*Centers the Game horizontally*/
    justify-content: center;

    /*Centers the Game vertically*/
    align-items: center;
}

标签: javascriptarrays

解决方案


在 this.update() 中,您想要删除数组中的第一个元素 - 但有两种正常机制。

if (this.tail.length > this.length) {
    this.tail.pop();  // removes the oldest snake section.
}

然而!

我提到的两种机制是:

  1. 每次重绘世界。
  2. 重新绘制蛇的更新。(即通过在此处画一个空白来擦除尾巴。)

你必须选择,一个,我不确定你现在在做什么。

要擦除它,您将绘制第 0 个元素。如果每次都绘制整个世界,那么从数组中移除就足够了。因为它只会绘制数组中的内容。

你有一个 update() 和 show() - 许多框架会调用这些函数 update() 和 draw(),而 update() 通常负责数学/数据操作(例如更新蛇点)和绘制() 根据数据绘制世界。看起来这就是你想要的。

你会遇到的问题是在你弹出第 0 个元素之后——当你到达 draw/show() 时它就不存在了。所以我建议如果你要保留这个,你每次都要绘制整个世界,否则,你将被迫在更新功能中绘制。


推荐阅读