0

Hey,

I am having some difficulty drawing my lines correctly using flash.Box2D. The fault isnt with box2D, rather with my math.
I attached a swf with the basic engine as well as some angles drawn on it.
Why doesnt the lines want to draw correctly for anything greater than +-40 degrees?

Here is the code used to draw the line, from the mouse events till the actual drawing.

        public function beginDraw(e:Event):void{
            if (!drawing){
                beginX = mouseX;
                beginY = mouseY;
                drawing = true;
            }
        }
        public function endDraw(e:Event):void{
            if (!drawing){
            }
            else{
                endX = mouseX;
                endY = mouseY;
                drawLine(beginX,beginY,endX,endY);
                drawing = false;
            }
        }

        public function drawLine(bX:Number,bY:Number,eX:Number,eY:Number):void{
            var line:b2PolygonShape= new b2PolygonShape();
            var lineBd:b2BodyDef = new b2BodyDef();
            var lineB:b2Body;
            var distancevar:Number = distance(bX,bY,eX,eY);
            lineBd.position.Set( (bX+eX)/2 / pixelsPerMeter, (bY+eY)/2 / pixelsPerMeter);//Line is drawn from middle hence /2
            line.SetAsBox((distancevar/2)/pixelsPerMeter, 4/pixelsPerMeter/2);
            lineB = world.CreateBody(lineBd); // Box2D handles the creation of a new b2Body for us.
            lineB.CreateFixture2(line); 
            lineB.SetAngle((eY / pixelsPerMeter-bY / pixelsPerMeter)/(eX / pixelsPerMeter-bX / pixelsPerMeter));

        }

Thanks alot

3
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by Mbot
0

The value you pass into SetAngle is:

tan(angle) = (eY / pixelsPerMeter-bY / pixelsPerMeter)/(eX / pixelsPerMeter-bX / pixelsPerMeter)

So, to get the angle (unless SetAngle for some reason accepted the tangent of the angle) you'd have to take the inverse tangent. Btw, that function can be reduced:

(eY / pixelsPerMeter-bY / pixelsPerMeter)/(eX / pixelsPerMeter-bX / pixelsPerMeter)
=[(eY - bY) / pixelsPerMeter]/[(eX - bX) / pixelsPerMeter]
=(eY - bY) / (eX - bX)

We're looking for a ratio instead of a measurement, so scale shouldn't matter.

0

Inverse tangent, as in: arctan((eY-bY)/(eX-bX)). One other thing, you should do a check for the case when eX-bX returns 0. In this case, you would directly set the angle to 90 (or pi/2), or whatever the angle straight up is if 0 degrees isn't horizontal.

Edited by nmaillet

0

For whoever is interested, I sent the slope as my setangle() value, it had to be a radian value. Fixed all the problems.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.