xxxxxxxxxx
76
// An example of using the keyboard to move a circle
// Jump the circle with SPACE BAR. Check to see if it
// goes off the screen too.
//
// Changes to red when mouse is over circle
//
// By Jon Froehlich
// http://makeabilitylab.io
//
// See:
// - https://learning.oreilly.com/library/view/make-getting-started/9781457186769/ch05.html#response
// - https://medium.com/comsystoreply/introduction-to-p5-js-9a7da09f20aa
let diameter = 30;
let x;
let y;
let pixelIncrement = 15;
let jump = 40;
function setup() {
createCanvas(600, 400);
noStroke();
x = width / 2;
y = height / 2;
fill(0);
}
function draw() {
background(204);
// check if the mouse is over the circle
if(dist(x, y, mouseX, mouseY) <= diameter/2){
fill(255, 0, 0);
stroke(0);
}else{
fill(0);
}
ellipse(x, y, diameter);
}
function keyPressed() {
// don't put any drawing code in here!
if (keyCode === LEFT_ARROW) {
x = x - pixelIncrement;
} else if (keyCode === RIGHT_ARROW) {
x = x + pixelIncrement;
} else if(keyCode == DOWN_ARROW){
y = y + pixelIncrement;
}else if(keyCode == UP_ARROW){
y = y - pixelIncrement;
}
// use space bar for jump!
if(key == ' '){
y = y - jump;
}
// check to make sure it doesn't go offscreen
let radius = diameter / 2;
if(x - radius < 0){
x = radius;
}else if(x + radius > width){
x = width - radius;
}
if(y - radius < 0){
y = radius;
}else if(y + radius > height){
y = height - radius;
}
}