基于p5.js实现递归树木在cos(20)与-cos(20)角度间平滑旋转的技术问询
Smooth Rotating Recursive Tree in p5.js
I get it, you want your recursive tree to swing smoothly between two angles—no clunky manual loops needed, since p5.js has built-in tools to handle this naturally! Here's how to implement the smooth rotation using the automatic draw() loop and a cosine function for that natural, easing swing effect:
Step-by-Step Breakdown
- Leverage
frameCountfor Oscillation: TheframeCountvariable increments every timedraw()runs, which we can feed into a cosine function to get a smooth, repeating value between -1 and 1. - Map to Your Desired Angle Range: Multiply the cosine result by your maximum rotation angle to swing between
-maxAngleandmaxAngleexactly as you want. - Rotate at the Tree Base: Apply the rotation after translating to the tree's root so the entire tree swings around its base, not the canvas origin.
Modified Working Code
let rotationSpeed = 0.02; // Adjust to make the swing faster/slower let maxRotationAngle = cos(radians(20)); // Swings between -cos(20°) and cos(20°) var strokeValue = 1; function setup() { const canvas = createCanvas(540, 400); frameRate(8); } function draw() { background(220); const branchAngle = PI/8; // Local variable for branch split angle translate(250, height); // Calculate smooth rotation using cosine and frameCount const currentRotation = cos(frameCount * rotationSpeed) * maxRotationAngle; rotate(currentRotation); branch(90); } function branch(length) { strokeWeight(strokeValue); line(0, 0, 0, -length); // Fixed line start to (0,0) for precise positioning translate(0, -length); if (length > 4) { // Right branch push(); rotate(branchAngle); branch(length * 0.72); pop(); // Left branch push(); rotate(-branchAngle); branch(length * 0.72); pop(); // Middle branch push(); rotate(-branchAngle * 0.2); branch(length * 0.3); pop(); } }
Key Changes & Notes
- Fixed Line Positioning: Adjusted the
line()call to start at(0,0)instead of(1,1)—this ensures the tree starts exactly at the translated base position, eliminating a tiny offset. - Cleaner Variable Scope: Changed
angletobranchAngleand made it a local variable indraw()to avoid global scope conflicts. - Tunable Speed: The
rotationSpeedvariable lets you tweak swing speed—increase it for faster movement, decrease for a slower, more natural sway. - Organic Easing: Using cosine ensures the rotation slows down at the extremes of the swing (just like a real tree), making the animation feel smooth and natural instead of jerky.
If you wanted to swing between 20 degrees and -20 degrees instead of cos(20°), just replace maxRotationAngle with radians(20)—the rest of the code works exactly the same way!
内容的提问来源于stack exchange,提问作者Yassine Mrabet
相关产品推荐
相关产品推荐

