Here’s how you can modify the code to set the starting and ending height of the square, allowing the square to move along a sigmoid-like curve that starts and ends at specified heights.
let t = 0; // Time variable to control the position on the curve
let speed = 0.02; // Speed of the movement
let startHeight = 50; // Starting height of the square
let endHeight = 350; // Ending height of the square
function setup() {
createCanvas(400, 400); // Create a canvas
}
function draw() {
background(220); // Clear the canvas
// Sigmoid function to calculate x and y positions
let x = map(t, 0, 1, 50, width - 50); // Map t to a range for x (left to right)
let sigmoidValue = 1 / (1 + exp(-10 * (t - 0.5))); // Sigmoid function value (0 to 1)
let y = map(sigmoidValue, 0, 1, startHeight, endHeight); // Map sigmoid to start and end heights
// Draw the square
rect(x - 25, y - 25, 50, 50); // Centered square at (x, y)
// Increment t to move along the curve
t += speed;
// Reset t when it goes out of bounds
if (t > 1) {
t = 0;
}
}
-
Added
startHeight
andendHeight
:- These variables define the starting and ending vertical positions of the square.
-
Mapped Sigmoid Output:
- The sigmoid function outputs a value between 0 and 1. This value is then mapped to the range
[startHeight, endHeight]
usingmap()
.
- The sigmoid function outputs a value between 0 and 1. This value is then mapped to the range
-
Dynamic Heights:
- You can now adjust
startHeight
andendHeight
to customize the vertical range of motion.
- You can now adjust
-
To make the square start low and end high:
let startHeight = 300; let endHeight = 100;
-
To restrict vertical movement to the middle of the canvas:
let startHeight = 150; let endHeight = 250;
This modification gives you full control over the vertical range of the sigmoid motion while keeping the horizontal movement consistent across the canvas.