
In his recent Live Stream, Daniel Shiffman announced he would make a fidget spinner simulation in the near future. Inspired by this idea, Simon has jotted down some code for the fidget spinner project. The code and part of the code description both come from The Nature of Code, Example 2.6. Simon explains that the code below has a non-static radius, because he is dealing with x and y coordinates and not angles (i.e. not spinning but moving to where the mouse is). He says he is going to use that code as a foundation. The second step will be to rely on angles instead of x and y coordinates. The third step will be to rotate have the fidget spinner keep rotating and to apply a friction force to make it stop eventually.
Simon recorded this video, where he ponders on the possibilities for the fidget spinner code:
Simon wrote the rest of this post:
Description:
This is the code for clicking and dragging an object around the screen.
To do that, you need the following data:
- mass (radius of the object)
- location (position of the object)
- dragging (Is the object being dragged?)
- rollover (Is the mouse over the object?)
- dragOffset (offset for when the object is clicked on)
And the following functionality:
- clicked (checks if the object is hovered over and sets dragging to true)
- hover (checks if the object is hovered over and sets rollover to true)
- stopDragging (sets dragging to false)
- drag (moves the object around the screen according to the mouse)
Code and Pseudocode:
Fidget Spinner Simulation
– Prepare mouse interaction code
– Data (mass, location, dragging, rollover, dragOffset)
– Functionality (clicked, hover, stopDragging, drag)
– Code (Mover)
– Variables
float mass;
PVector location;
boolean dragging = false;
boolean rollover = false;
PVector dragOffset;
– Functions
void clicked(int mx, int my) {
float d = dist(mx,my,location.x,location.y);
if (d < mass) {
dragging = true;
dragOffset.x = location.x-mx;
dragOffset.y = location.y-my;
}
}
void hover(int mx, int my) {
float d = dist(mx,my,location.x,location.y);
if (d < mass) {
rollover = true;
}
else {
rollover = false;
}
}
void stopDragging() {
dragging = false;
}
void drag() {
if (dragging) {
location.x = mouseX + dragOffset.x;
location.y = mouseY + dragOffset.y;
}
}
– Code (Main)
– Variables
Mover m;
– Functions
void draw() {
m.drag();
m.hover(mouseX,mouseY);
}
void mousePressed() {
m.clicked(mouseX,mouseY);
}
void mouseReleased() {
m.stopDragging();
}