Hey Kirupa! This is my first post here, and I’ve got a noodle-scratcher. (Well, it is to me anyway.)
I’m making an interactive simulation of a wrench (well, caliper, really) which the user can click and drag around and close the jaws on a number of nuts, pipes, etc, but I’m having a hard time nailing down the right kind of collision physics to do this convincingly.
After looking around at a few physics engines, I thought Corey O’Neil’s Collision Detection Kit had a lot of promise, but I couldn’t quite get a handle on implementing it since its examples involve falling/moving items with predetermined gravity, friction, etc, as well as my … erm … “complete ineptitude with trigonometry.”
Blindly attempting to reconfigure the example code didn’t work (some variables along the line - probably vx/vy - return as NaN or undefined, and the caliper’s coordinates just go to 0,0):
var vx:Number = 0;
var vy:Number = 0;
var collisions:Array;
var collisionGroup:CollisionGroup = new CollisionGroup(caliper, object);
addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void {
collisions = collisionGroup.checkCollisions();
if(collisions.length){
var angle:Number = collisions[0].angle;
var sin:Number = Math.sin(angle);
var cos:Number = Math.cos(angle);
var vx0:Number = caliper.vx * cos + caliper.vy * sin;
var vy0:Number = caliper.vy * cos - caliper.vx * sin;
vx0 = .4;
caliper.vx = vx0 * cos - vy0 * sin;
caliper.vy = vy0 * cos + vx0 * sin;
trace(vx0);
caliper.y += caliper.vy;
caliper.x += caliper.vx;
}
}
And when I tried substituting the constants with mouse speed detection, the result was just sloppy (the caliper shakes when hitting the object, and can still pass through the object at some angles):
var prevPt:Point=new Point(mouseX,mouseY);
var lastPt;
var dir;
var Mspeed;
var xspeed;
var yspeed;
addEventListener(Event.ENTER_FRAME,mouseSpeed);
function mouseSpeed(e:Event){
xspeed=Math.abs(mouseX-prevPt.x);
yspeed=Math.abs(mouseY-prevPt.y);
Mspeed=xspeed+yspeed;
prevPt=new Point(mouseX,mouseY);
}
var vx:Number = 0;
var vy:Number = 0;
var collisions:Array;
var collisionGroup:CollisionGroup = new CollisionGroup(caliper, object);
addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void {
collisions = collisionGroup.checkCollisions();
if(collisions.length){
var angle:Number = collisions[0].angle;
var sin:Number = Math.sin(angle);
if(angle>0){
caliper.y += yspeed;
caliper.x += xspeed;
}
if(angle<0){
caliper.y -= yspeed;
caliper.x -= xspeed;
}
trace(angle);
}
}
All in all, I’ve just created a huge mess.
So, what am I doing wrong? Is there a better way of approaching the collisions? General thoughts?
Any input would be much appreciated. Thanks!
~gyz