the problem with mouse and the character is in the translate(). note: all the lines below translate(), the Y and X are relative to 0. meaning if you
translate(100, 200);
ellipse(30, 40, 10, 10);
youāll get the actual X and Y:
X = 100 + 30 = 130; //and
Y = 200 + 40 = 240;
so to solve this problem, you can pick some constants for X and Y (in this case i picked from the body of the character, so the body will in the origin (0,0)) and subtract every X and Y with those constants.
fill(255,224,189);
rect(100,100,60,50); // the body
fill(210,105,30);
rect(110,120,15,5);
rect(135,120,15,5);
to this
fill(255,224,189);
rect(0,0,60,50); // the body
fill(210,105,30);
rect(10, 20,15,5);
rect(35,20,15,5);
And for the second problem, you can use collision detection function for Rectangle and circle.
first, define the Hat x and y. in this case the hat x and y:
//below translate
hatX = -15;
hatY = -4;
actual hatX and hatY are
hatX = mouseX - 45; // + x Translate
hatY = 376; // + y Translate
so,
boolean ballHitsHat() {
// Rectangle and circle collision detection
if (ballPos.y + ballRadius > hatY && ballPos.x + ballRadius > hatX && ballPos.x + ballRadius < hatX + hatW) {
return true;
}
return false;
}
finally, iāve got something done for you, some adjustments and corrections
PVector ballPos;
PVector speed;
PVector gravity;
float friction = 0.8;
float ballRadius = 25;
float hatX;
float hatY = 376;
float hatW = 90;
float hatH = 4;
void setup() {
size(640, 480);
ballPos = new PVector(0, 0);
speed = new PVector(3, 1);
gravity =new PVector(0, 1);
}
void draw() {
background(44, 56, 245);
fill(2, 188, 34);
noStroke();
rect(0, 440, width, height);
updateBall();
checkBall();
drawPuppy();
drawBall();
}
void updateBall() {
speed.add(gravity);
ballPos.add(speed);
}
boolean ballHitsHat() {
// Rectangle and circle collision detection
if (ballPos.y + ballRadius > hatY && ballPos.x + ballRadius > hatX && ballPos.x + ballRadius < hatX + hatW) {
return true;
}
return false;
}
void checkBall() {
if (ballHitsHat()) {
speed.y *= -1;
}
// checking Edges
if (ballPos.x > width - ballRadius) {
if (speed.x > 0) speed.x *= -1;
} else if (ballPos.x < ballRadius) {
if (speed.x < 0) speed.x *= -1;
}
if (ballPos.y > height - ballRadius - 34) {
ballPos.y = height - ballRadius - 34;
speed.y *= -friction;
}
}
void drawBall() {
fill(180);
stroke(0);
strokeWeight(2);
ellipse(ballPos.x, ballPos.y, ballRadius*2, ballRadius*2);
}
void drawPuppy() {
pushMatrix();
hatX = mouseX - 45;
translate(mouseX - 30, 380);
fill(255, 224, 189);
rect(0, 0, 60, 50);
fill(210, 105, 60, 50);
rect(10, 20, 15, 5);
rect(35, 20, 15, 5);
fill(0);
ellipse(30, 36, 10, 2);
fill(0);
rect(-15, -4, hatW, hatH);
fill(0);
rect(10, 50, 40, 20);
fill(0);
rect(10, 70, 5, 10);
rect(45, 70, 5, 10);
popMatrix();
}