2017-05-04 73 views
1

你好我無法理解在哪裏和哪裏不能使用p5.js方法。在這種codepen在對象內部使用p5.js寬度和高度方法的問題

var bubble = { 
    x: 200, 
    y: 200, 
    display: function() { 
    stroke(255); 
    strokeWeight(4); 
    noFill(); 
    ellipse(this.x, this.y, 24, 24); 
    }, 
    move: function() { 
    this.x = this.x + random(-1, 1); 
    this.y = this.y + random(-1, 1); 
    } 
} 

function setup() { 
    createCanvas(600, 400); 

} 

function draw() { 
    background(0); 
    bubble.display(); 
    bubble.move(); 
    ellipse(width/2,height/2,50,50) 
} 

如果我替換x和y值與我的「泡沫」對象內部,例如,「寬度/ 2」和「高度/ 2」 - 控制檯打印「寬度」沒有被定義?如果我在draw()函數內使用相同的方法,它可以正常工作。我猜這是一個範圍界定問題?但不知道如何解決它。非常感謝。

回答

1
var bubble = { 
    init : function(){ 
    this.x = width/2; 
    this.y = height/2; 
    }, 
    display: function() { 
    stroke(255); 
    strokeWeight(4); 
    noFill(); 
    ellipse(this.x, this.y, 24, 24); 
    }, 
    move: function() { 
    this.x = mouseX; 
    this.y = mouseY; 
    } 
} 

我不能告訴你爲什麼它不工作,我不出來,但這裏是一個可行的解決方案

+0

感謝您的時間 – James

+0

這個工作,因爲匿名的情況下函數在p5實例的顯示和設置方法中的範圍是正確的,而普通對象的範圍是全局窗口。 p5作者通過支持這樣的全局方法使這變得複雜。 – Bosworth99