hi,
I’m just tarting to learn to code and I want my initial rectangle to move right when my mouse is clicked and I can’t seem to get the code right and I just can’t figure out why. If someone could please run it and tell me what I’m doing wrong that would be great.
Thanks!
Here is my code:
let col;
let rectX;
//let col2
function setup() {
createCanvas(600, 400);
col = map(mouseX, 250, 350, 0, 255);
//col2=map(mouseY,150,250,0,255)
rectX = 300;
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
noFill();
if (mouseX > 250 && mouseX < 350 && mouseY < 250 && mouseY > 150) {
fill(col, 0, 0);
}
rectMode(CENTER);
rect(rectX, 200, 100, 100);
rectX = 300;
function mousePressed() {
if (mouseX > 250 && mouseX < 350 && mouseY < 250 && mouseY > 150) {
fill(255, 0, 0);
rectMode(CENTER);
rect(rectX, 200, 100, 100);
rectX = rectX + 0.1
;
}
}
col = map(mouseX, 250, 350, 0, 255);
}
Hello, and welcome to the forum!
Great to have you here!
Remarks
function mousePressed()
was inside draw(). Bad
Also you had rectX = 300;
in draw() (and not only in setup()
) so it reseted rectX
every time. Bad.
A change of + 0.1 might be too small. I changed this to +5
.
Full Sketch
let col;
let rectX;
//let col2
function setup() {
createCanvas(600, 400);
col = map(mouseX, 250, 350, 0, 255);
//col2=map(mouseY,150,250,0,255)
rectX = 300;
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
noFill();
if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
fill(col, 0, 0);
}
rectMode(CENTER);
rect(rectX, 200, 100, 100);
// rectX = 300;
col = map(mouseX, 250, 350, 0, 255);
}
function mousePressed() {
if (mouseX > 250 && mouseX < 350 && mouseY < 250 && mouseY > 150) {
//fill(255, 0, 0);
//rectMode(CENTER);
//rect(rectX, 200, 100, 100);
rectX = rectX + 5;
}
}
Thanks for the response.
I wasn’t clear about it but I want the rectangle to move continuously when I moussePressed() rather than by a distance each time I press.
1 Like
let col;
let rectX;
let rectIsMoving=false;
//let col2
function setup() {
createCanvas(600, 400);
col = map(mouseX, 250, 350, 0, 255);
//col2=map(mouseY,150,250,0,255)
rectX = 300;
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
noFill();
if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
fill(col, 0, 0);
}
rectMode(CENTER);
rect(rectX, 200, 100, 100);
if(rectIsMoving)
rectX += 3;
col = map(mouseX, 250, 350, 0, 255);
}
function mousePressed() {
if (mouseX > 250 && mouseX < 350 && mouseY < 250 && mouseY > 150) {
//fill(255, 0, 0);
//rectMode(CENTER);
//rect(rectX, 200, 100, 100);
rectIsMoving=true;
}
}
thank you lots, very much appreciated
1 Like