Collision detection is acting weird in PJS
in
Processing with Other Languages
•
4 months ago
I'm working on a little platformer game, and in PJS objects appear to be bouncing off of invisible walls - a behavior that does not appear in Java Mode. I suspect the problem lies in how Javascript is (mis)handling the collision code, but I'm just not seeing it:
- PVector collisions(PhysicsThing thing) {
- PVector force = new PVector(0,0);
- Circle c = thing.circ;
- for (int i=0; i < segments.size(); i++) {
- LineSegment s = (LineSegment) segments.get(i);
- if (PVector.dist(s.a, thing.location) < cellSize*2) {
- if (collides(c, s)) {
- PVector f = normalVector(c, s);
- f.mult(0.2);
- PVector proj = project(thing.velocity, PVector.sub(s.a, s.b));
- proj.mult(0.1);
- f.add(proj);
- force.add(f);
- }
- }
- }
- force.normalize();
- force.mult(0.5);
- return force;
- }
- boolean collides(Circle c, LineSegment s) {
- return magSq(normalVector(c, s)) < c.radius*c.radius;
- }
- PVector normalVector(Circle c, LineSegment s) {
- PVector seg = PVector.sub(s.b, s.a);
- PVector proj = project(PVector.sub(c.location, s.a), seg);
- if (PVector.angleBetween(proj, seg) >= 3.14) {
- return PVector.sub(c.location, s.a);
- } else if (magSq(proj) > magSq(seg)) {
- return PVector.sub(c.location, s.b);
- } else {
- return PVector.sub(c.location, PVector.add(s.a, proj));
- }
- }
- PVector project(PVector v, PVector onto) {
- PVector proj = onto.get();
- proj.normalize();
- proj.mult(PVector.dot(v, proj));
- return proj;
- }
The full source code is here:
https://dl.dropboxusercontent.com/u/61122505/sgould_moe.zip
1