I have a single class Part and two objects from this class part1 and part2. I would like to be able to have these objects bounce off of each other when they collide using methods. I am able to do this with functions outside the class, but would like to be able to do it with methods purely inside the class, so I can add objects without having to add each object to my watchforpartcollision function.
This is code works but I would like the function to be a method:
void draw() {
background(255);
part1.drawpart();
part2.drawpart();
part1.watchforcollision();
part1.applymovement();
part2.watchforcollision();
part2.applymovement();
watchforpartcollision(); //function I would like to make a method
}
...
void watchforpartcollision() {
if (dist(part1.x + part1.size/2, part1.y + part1.size/2,
part2.x + part2.size/2, part2.y + part2.size/2) <= (part1.size)) {
partcolide();
}
}
void partcolide() {
part1.xspeed = (part1.xspeed * part2.oldxspeed) + part2.oldxspeed;
part1.yspeed = (part1.yspeed * part2.oldyspeed) + part2.oldyspeed;
part2.xspeed = (part2.xspeed * part1.oldxspeed) + part1.oldxspeed;
part2.yspeed = (part2.yspeed * part1.oldyspeed) + part1.oldyspeed;
}
This is what I would like:
void draw() {
background(255);
drawcursor();
part1.drawpart();
part2.drawpart();
part1.watchforcollision(); //method I would like to add function too
part1.applymovement();
part2.watchforcollision(); //method I would like to add function too
part2.applymovement();
}
...
class Part {
...
void watchforcollision() {
...
if (dist(x + size/2, y + size/2, x + size/2, y + size/2) <= (size)) {
/*This ^ is the line that messes it up because it's checking the distance
between the same two things*/
partcolide();
}
}
...
void partcolide() {
xspeed = (xspeed * oldxspeed) + oldxspeed;
yspeed = (yspeed * oldyspeed) + oldyspeed;
xspeed = (xspeed * oldxspeed) + oldxspeed;
yspeed = (yspeed * oldyspeed) + oldyspeed;
}
}
Any help would be much appreciated!
Thank you!
If you want to move the collision logic into the class, then you'll need to pass in the object you want to collide with when you make the method call:
part1.watchforcollision(part2);
Inside the class:
void watchforpartcollision(Part obj) { // `obj` is the Part object passed in
if (dist(x + size/2, y + size/2,
obj.x + obj.size/2, obj.y + obj.size/2) <= (size)) {
partcolide();
obj.partcolide(); // apply the collision to the second object too
}
}