...
Code Block |
---|
language | js |
---|
linenumbers | true |
---|
|
let startPos;
let endPos;
let curTime = 0;
let animSpeed = 5;
let animDuration = 2000;
let drawFlag = false;
function setup()
{
createCanvas(640, 480);
smooth();
startPos = createVector(0,0);
endPos = createVector(0,0);
}
function draw()
{
background(51);
// calc. the anim time
curTime += animSpeed;
if(curTime >= animDuration) {
curTime = 0;
}
// calc. the proportion of completion in the animation
var normTime = curTime * 1.0 / animDuration;
if(drawFlag)
{
stroke(255);
line(startPos.x,startPos.y,endPos.x,endPos.y);
// calculate the position of the circle on the line
let dir = p5.Vector.sub(endPos, startPos);
let pos = p5.Vector.add(startPos, p5.Vector.mult(dir,normTime));
ellipse(pos.x,pos.y, 20,20);
}
}
function mousePressed()
{
drawFlag = true;
curTime = 0;
startPos.set(mouseX,mouseY,0);
get(startPos.x, startPos.y);
}
function mouseDragged()
{
endPos.set(mouseX,mouseY,0);
}
function mouseReleased()
{
drawFlag = false;
print("released");
} |
Exercise 11
Modified the example to do the following:
- The start and end point of the the animation path is to be defined by mouse click
- The ellipse should move forward and backwards endlessly
Example AnswerÂ
Code Block |
---|
language | js |
---|
linenumbers | true |
---|
collapse | true |
---|
|
let startPos;
let endPos;
let curTime = 0;
let animSpeed = 5;
let animDuration = 2000;
let drawFlag = false;
let animEndFlag = false;
let clickFlag = false;
function setup()
{
createCanvas(640, 480);
smooth();
startPos = createVector(0,0);
endPos = createVector(0,0);
}
function draw()
{
background(51);
// calc. the anim time
curTime += animSpeed;
if(curTime >= animDuration) {
curTime = 0;
}
// calc. the proportion of completion in the animation
var normTime = curTime * 1.0 / animDuration;
if(drawFlag)
{
stroke(255);
line(startPos.x,startPos.y,endPos.x,endPos.y);
// calculate the position of the circle on the line
let dir = p5.Vector.sub(endPos, startPos);
// move the circle on the line
let pos = p5.Vector.add(startPos, p5.Vector.mult(dir,normTime));
ellipse(pos.x,pos.y, 20,20);
}
}
function mousePressed()
{
if (clickFlag == false) {
stroke(255, 0, 0);
fill(255,0,0);
drawFlag = true;
curTime = 0;
startPos.set(mouseX, mouseY, 0);
clickFlag = true;
} else {
stroke(255);
fill(255);
endPos.set(mouseX, mouseY, 0);
clickFlag = false;
}
print(clickFlag);
}
function mouseMoved() {
if (clickFlag == true) {
endPos.set(mouseX, mouseY, 0);
}
} |
...