Javascript / p5.js变量问题

时间:2017-05-13 21:46:15

标签: javascript p5.js

我正在使用p5.js并为一个小对象创建了一个构造函数。 当我尝试更新这些对象的列表时,一切都开始以一种非常奇怪的方式影响其他对象。为什么它会像那样?

以下是我的草图的简化版本:

var pellets = [],
    cells = []

function setup() {
    createCanvas(400, 300)
    // ...

    for (var i = 0; i < 3; i++) {
        var pos = createVector(random(width), random(height))
        var col = color("#ff0000")
        cells.push(new Bot(pos, col, pelletMiddle))
    }

    // ...
}

function draw() {
    for (var i in pellets) {
        cells[i].update()
        cells[i].draw()
    }
}

这是构造函数:

function Bot(position, col, mass) {
    //private:
    position = position.copy()
    var velocity = createVector()
    var acceleration = createVector()

    //public:
    this.nearby = []
    this.draw = function () {
        fill(col)
        ellipse(position.x, position.y, mass)
    }

    this.getPosition = function () {
        return position.copy()
    }

    this.getDistance = function (vector) {
        return position.dist(vector)
    }

    this.update = function () {
        position.add(velocity)
        velocity.add(acceleration).limit(5)

        var pos = createVector(),
            dist = Infinity
        for (var i in pellets) {
            var lpos = pellets[i].getPosition()
            if (this.getDistance(lpos) < dist) {
                dist = this.getDistance(lpos)
                pos = lpos
            }
        }
        acceleration = pos.sub(position).limit(random(0.5))
    }
}

1 个答案:

答案 0 :(得分:0)

经过几个小时的修补后,我发现了这个问题...... 我在1 | 1. Hello 2 | 2. I am Fine 3 | 3. What about U ? 4 | var之前缺少velocity

所以accelerationvelocity只是全局变量。