2011-04-28 83 views
0

我正在處理語言和有一個這樣的代碼:在另一個類我要調用的方法increaseCircle()緩慢處理繪製方法?

int fatness=30; 
int step=20; 

void drawCircle() { 
fill(48, 139, 206); 
ellipse(width - fatness, height - fatness, fatness, fatness); 
} 

void increaseCircle(){ 
fatness = fatness + step; 
} 

。不過,我希望它慢慢變大。我的意思是step使我的代碼更大,但我希望它在2秒內變得更大,如果可能的話使用動畫。我怎樣才能做到這一點?

編輯:當我從那個類中定義一個對象並調用increaseCircle方法時,它變得越來越大,不停止嗎?

回答

3

聽起來像你需要更新基於時間的值。

如果您存儲開始時間,您可以始終檢查使用millis()函數已經過了多少時間。

一旦你知道了多少時間過去了,你可以將這種差異分爲想要更新變量的時間長度(在你的情況下)。

這會給你0.0和1.0之間的值,你可以用它來縮放/乘到你變量的最終期望值(例如,肥胖從20到200)。

這裏就是我的意思是:

int startTime; 
int duration = 1000; 
float startValue = 20; 
float endValue = 200; 
float currentValue = startValue; 

void setup(){ 
    size(400,400,P2D); 
    ellipseMode(CENTER); 
    startTime = millis(); 
} 
void draw(){ 
    background(255); 
    increaseCircle(); 
    drawCircle(); 
} 
void drawCircle() { 
fill(48, 139, 206); 
ellipse(width - currentValue, height - currentValue, currentValue, currentValue); 
} 

void increaseCircle(){ 
    float progress = (float)(millis()-startTime)/duration;//millis()-startTime = difference in time from start until now 
    if(progress <= 1.0) currentValue = startValue + (endValue * progress);//the current value is the final value scaled/multiplied by the ratio between the current duration of the update and the total duration 
} 
void mousePressed(){//reset value and time 
    currentValue = startValue; 
    startTime = millis(); 
} 
void keyPressed(){//update duration 
    if(key == '-') if(duration > 0) duration -= 100; 
    if(key == '=' || key == '+') duration += 100; 
    println("duration: " + duration); 
} 

在這個簡單的演示中,你可以點擊重置動畫和使用-=鍵增加或減少動畫的持續時間。

如果您對處理中使用外部庫感到滿意,則應該查看this library

您可以運行波紋管演示:

var startTime; 
 
var duration = 1000; 
 
var startValue = 20; 
 
var endValue = 200; 
 
var currentValue = startValue; 
 

 
function setup(){ 
 
    createCanvas(400,400); 
 
    ellipseMode(CENTER); 
 
    startTime = millis(); 
 
} 
 
function draw(){ 
 
    background(255); 
 
    increaseCircle(); 
 
    drawCircle(); 
 
} 
 
function drawCircle() { 
 
fill(48, 139, 206); 
 
ellipse(width - currentValue, height - currentValue, currentValue, currentValue); 
 
} 
 

 
function increaseCircle(){ 
 
    var progress = (float)(millis()-startTime)/duration;//millis()-startTime = difference in time from start until now 
 
    if(progress <= 1.0) currentValue = startValue + (endValue * progress);//the current value is the final value scaled/multiplied by the ratio between the current duration of the update and the total duration 
 
} 
 
function mousePressed(){//reset value and time 
 
    currentValue = startValue; 
 
    startTime = millis(); 
 
} 
 
function keyPressed(){//update duration 
 
    if(key == '-') if(duration > 0) duration -= 100; 
 
    if(key == '=' || key == '+') duration += 100; 
 
    println("duration: " + duration); 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>