dragging nodes
in
Programming Questions
•
4 months ago
this is a code about dragging nodes where you should be able first to decide the lenght of the line and the numbers of nodes and then to makethe nodes draggable using mouse actions. The sliders work perfectly but the drag and drop function to move the nodes independently doesn't work. Do you have any ideashow to solve it??
Thank you in advance
This is the code
//Code===========================================================================
import controlP5.*;
ControlP5 cp5;
Node dragNode = null;
ArrayList nodes1;
float mx, my;
float x = 20;
float y = 200;
float w= 300;
float d=400;
float offset = 20;
int pointsA=12;
void setup() {
size(1200, 800);
smooth();
cp5 = new ControlP5(this);
//Sliders_______________________________________________________________________________
cp5.addSlider("pointsA")
.setPosition(100, 50)
.setRange(3, 20)
;
cp5.addSlider("w")
.setPosition(100, 150)
.setRange(3, 550)
;
}
void draw() {
background(255);
nodes1 = new ArrayList();
//Lines costruction_______________________________________________________________________________
stroke(255);
//points and parameter for subdivision line A
float stepA=dist(x+w-offset, y+offset, x+w-offset, y+d-offset)/pointsA;
for (float ptsparA = 0; ptsparA < dist(x+offset, y+offset, x+w-offset, y+offset); ptsparA+=stepA) {
Node n = new Node(x+offset+ptsparA, y+offset, 5);
nodes1.add(n);
}
//Nodes, polylines_______________________________________________________________________________
for (int i = 0; i < nodes1.size(); i++) {
Node n = (Node) nodes1.get(i);
n.draw();
stroke(1);
noFill();
beginShape();
for (int a = 0; a < nodes1.size(); a++) {
Node p1 = (Node)nodes1.get(a);
vertex(p1.x, p1.y);
}
endShape(CLOSE);
}
//interaction mouse_________________________________________________________________________________
}
void mousePressed() {
dragNode = null;
Node p1;
for (int i = 0; i < nodes1.size(); i++) {
p1 = (Node) nodes1.get(i);
if (p1.contains(mouseX, mouseY)) {
dragNode = p1;
}
}
}
void mouseDragged() {
if (dragNode != null) {
//dragNode.x = mouseX;
//dragNode.y = mouseY;
mx = constrain(mouseX, x+offset, x+w-offset);
my = constrain(mouseY, y+offset, y+d-offset);
dragNode.x = mx;
dragNode.y = my;
}
}
void mouseReleased() {
dragNode = null;
}
//class===========================================================================
class Node {
float x, y, r;
Node(float x, float y, float r) {
this.x = x;
this.y = y;
this.r = r;
}
void draw() {
fill(255, 59, 59);
stroke(60);
strokeWeight(1);
ellipse(x, y, r * 2f, r * 2f);
}
boolean contains(float x, float y) {
float dx = this.x - x;
float dy = this.y - y;
return sqrt(dx * dx + dy * dy) <= r;
}
}
1