出于某种奇怪的原因,下面的代码不会产生预期的效果。正弦波很好且功能强大,下面的代码片段完美运行,除了向前移动,这是颠簸的。
我正在使用 millis() 并除以 1000 以转换为秒,但效果仍然会产生我使用 second() 函数所期望的形式 - 正弦波每 1 秒向前移动一次。我希望线条平滑地水平移动,就像正弦波线垂直移动一样。我做错了什么?
int cyclesBeforeStopping = 4;
int distanceBeforeStopping = 400;
float frequency = 0.2; // in Hz
float peak = 25; // Highest point of wave
float trough = 275; // Lowest point of wave
float amplitudeOffset;
float forwardOffset;
float timeUntilStop = (1 / frequency) * cyclesBeforeStopping;
void setup(){
size(600,300);
frameRate(50);
forwardOffset = ForwardOffset();
}
void draw(){
background(255);
float forwardOffsetNow = forwardOffset * (millis() / 1000);
// Guidelines
line(50 + forwardOffsetNow, peak, 100 + forwardOffsetNow, peak);
line(50 + forwardOffsetNow, trough, 100 + forwardOffsetNow, trough);
// Sine line
float newPosition = NewPosition();
line(50 + forwardOffsetNow, newPosition, 100 + forwardOffsetNow, newPosition);
}
float ForwardOffset() {
float forwardOffsetVar = (distanceBeforeStopping) / timeUntilStop;
return forwardOffsetVar;
}
float NewPosition() {
float omega = TWO_PI * frequency;
float amplitude = trough - peak;
float halfway = peak + amplitude / 2;
float newPosition = halfway - (amplitude * sin(omega * millis() / 1000) / 2);
return newPosition;
}