Created
April 3, 2017 20:52
-
-
Save nataliefreed/c83c1aa5d339208fb8b5a850e9988190 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var circles; | |
var currentDragged; | |
var clickRadius = 50; | |
function setup() { | |
createCanvas(500, 500); | |
imageMode(CENTER); | |
circles = []; | |
circles.push(new DraggableImage("p5js-beta.svg", 3 * width / 4, height / 2, clickRadius, color(0, 100, 0, 150))); | |
circles.push(new DraggableImage("p5js-beta.svg", width / 2, height / 2, clickRadius, color(0, 0, 100, 150))); | |
circles.push(new DraggableImage("p5js-beta.svg", width / 4, height / 2, clickRadius, color(255, 0, 255, 150))); | |
} | |
function draw() { | |
background(100); | |
for (var i = 0; i < circles.length; i++) { | |
circles[i].update(); | |
} | |
for (var i = circles.length - 1; i >= 0; i--) //draw backwards so first will be on top | |
{ | |
circles[i].display(); | |
} | |
} | |
function DraggableImage(filename, centerX, centerY, tempRadius, tempColor) { | |
this.center = createVector(centerX, centerY); | |
this.fillColor = tempColor; | |
this.dragged = false; | |
this.clickOffset = createVector(0, 0); | |
this.img = loadImage(filename); | |
this.radius = tempRadius; | |
this.display = function() { | |
image(this.img, this.center.x, this.center.y); | |
} | |
this.isOver = function(x, y) { | |
//return true if distance between point and center is smaller than radius | |
if (dist(this.center.x, this.center.y, x, y) <= this.radius) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
this.update = function() { //move with mouse | |
if (this.dragged === true) { | |
if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) //don't let it get away! | |
{ | |
this.center.set(p5.Vector.add(createVector(mouseX, mouseY), this.clickOffset)); | |
} | |
} | |
} | |
this.setDragged = function(fromX, fromY) { | |
this.dragged = true; | |
this.clickOffset = p5.Vector.sub(this.center, createVector(fromX, fromY)); | |
} | |
this.releaseDragged = function() { | |
this.dragged = false; | |
} | |
} | |
function mousePressed() { | |
if (currentDragged == null) { | |
for (var i = 0; i < circles.length; i++) { | |
if (circles[i].isOver(mouseX, mouseY)) { | |
currentDragged = circles[i]; | |
currentDragged.setDragged(mouseX, mouseY); | |
} | |
} | |
} | |
} | |
function mouseReleased() { | |
if (currentDragged != null) { | |
currentDragged.releaseDragged(); | |
currentDragged = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment