Reputation: 45
I'm making a small interaction in p5.js where an ellipse moves when the mouse is pressed, then eases down to the start position when the mouse is released.
Code listed below:
var easing = 0.01;
var start = 290;
var x = 0;
var y = 190;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(220);
if (mouseIsPressed) {
ellipse (mouseX, mouseY, 20, 20);
} else {
var targetX = mouseX;
x += (mouseX - x) * easing;
ellipse(start, y, 20, 20);
}
}
Upvotes: 1
Views: 262
Reputation: 390
This should do the trick.
var easing = 0.01;
var startX = 290;
var startY = 190;
var x = 0;
var y = 0;
function setup() {
createCanvas(400, 200);
x = startX;
y = startY;
}
function draw() {
background(220);
if (mouseIsPressed) {
x = mouseX;
y = mouseY;
} else {
x += (startX - x) * easing;
y += (startY - y) * easing;
}
ellipse(x, y, 20, 20);
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
Upvotes: 2