xxxxxxxxxx
54
// Grab, move, and release the spinner.
// Simplified Coding TrainRectangle Grab:
// https://editor.p5js.org/codingtrain/sketches/In9e8j6t_
let angle = 0; // Angle of the spinner.
let previousAngle = 0; // Angle of the spinner in the previous frame.
let angularVelocity = 0; // Angular velocity of the spinner.
function setup() {
createCanvas(200, 200);
// The spinner will have no stroke and filled pink.
noStroke();
fill(240, 99, 164);
rectMode(CENTER); // When drawing rectangle, coordinates specify shape's centre.
angleMode(RADIANS); // Not actually required, since RADIANS is default.
}
// The mouse's heading when centered mid-canvas.
// Returns an angle in radians between -PI and PI.
function mouseHeading() {
let v = createVector(mouseX - width / 2, mouseY - height / 2);
return v.heading();
// Using trigonometry with arc tangent of rise over run.
//return atan2((mouseY - height / 2), (mouseX - width / 2));
}
function draw() {
// Clear the canvas purple.
background(146, 83, 161);
// Draw spinner rotated by current angle around canvas centre.
translate(width / 2, height / 2);
rotate(angle);
rect(0, 0, width * 0.8, height * 0.1);
// Save the angle from the previous frame.
previousAngle = angle;
if (mouseIsPressed) {
// Have spinner rotate using the mouse's heading.
angle = mouseHeading();
// Base spinner velocity on distance rotated since previous frame.
// Bug here if angle crosses -PI and PI, where delta becomes a sum.
angularVelocity = angle - previousAngle;
} else {
// Apply the current velocity to the angle.
angle += angularVelocity;
// Simple linear friction.
angularVelocity *= 0.98;
}
}