Flash, Flex and ActionScript Resources -
I have created a line2D object for 2D collision detection
HariBabu Suraneni
While I am working in as a Flash Developer, I have really entered into Flash Script writing even though I started my career with AS2 in 2007. From that humble begening, now I have grown up to a successfull AS3 programmer. In my process of learning, actionscript org has a major role as I Learnt so much from the published tutorials and forums. Now, I think I have learnt some new techniques that are rarely finding their place in these articles, I want to share my knowledge through some of the educative tutorials. 
By HariBabu Suraneni
Published on January 22, 2011
Line2D is not a DisplayObject. it is a mathematical object just like Point. it can calculate Intersection point of two Line2D objects, which in turn is the basis of collision detection. it can do all the complicated calculations like dot product and cross product and saves much time and brain for the programmer who use it.

About Line2D Object:Introduction

About Line2D Object:Introduction

Recently I have wrote a Line2D Class in AS3. It is a proud decendant of flash.geom.Point. Actually, I am intrigued by a thought:Why flash did not give us a Line next to Point and gave Rectangle directly? This curiosity haunted me from the begining: but  when I am doing a work which requires to know Intersection Point of a Line on another Line, then I felt a real pressure to know about it thoroughly. Basically I didn't have much knowledge in Math linear equations, But they are very Important to apply  in my work, what to do? So, I searched math reated internet sites vigorously and found that the related material is spread across the web randomly, without any integrity. Neccessity is the mother of all Inventions!  I took the responsibility to inegrate the knowledge what I acquired and I have assimilated all of that into a single Object.

Thus the Line2D object came into existance. In fact there are some static functions to the point class like distance and interpolate, and some public functions like equals, normalize, polar will serve to modify it in a way to create a Line to Push it up to the requirement. But it it is not sufficient for an advanced programming tasks. While I am doing online search, I found the functionalities of a line were more complicated. A line in mathematics has so many properties and functionalities unique to it, which are quite different to the Point. There is slope, which is very crucial for a line. And, we need to show normals on left and right. It's basic functionality  is to check and return Intersection Points with each one among all the lines we have created. And It also has to return touch points for any one of the created Points. Very importantly, It has to follow the mathematical y=mx+b equation with  precision. And  it has to bridge the gap between the mathematical calculations - which follow cartesian coordinate space - and the flash coordinate space. This is very important in scripted animation. Why because,  those who are using trigonometry in flash animations for angular displacement are now fallowing a tricky Y-Shift Logic- that is calculating all the basic things and applying a-ve value for y in the final step of calculations before applying angular motion for any of the displayobjects. I have observed that my Line2d Object is projecting itself by it's calculated values and rendering on Flash stage in a normal way without any abnormalities.

My line2D is purely a Mathematical Object and requires argument data in two ways:one is of two points, and the other is of  a start point,vx and vy. From this basic data, It will calculate all the relevant values like dx and dy, Length and Angle, Slope and Breadth (very Important in applying y=mx+b), And Normals Left and Right. All he Important Logic about a line entity is successfully clubbed into a single object Line2D class. After creating an instance of a line, we can alter its orientation through set/get public functions p0,p1,radAngle. In the below example, you may observe it is updating its Orientation beautifully.

Above sample shows basic rendering features. It's Instance Creation syntax would be like this;

[as]var my_Point1:Point=new Point(70,140);
var my_Point2:Point=new Point(72,40);

var line1Args:Array=new Array(pntPoint1,pntPoint2);
var my_Line1:Line2D=new Line2D(line1Args);

As I explained you earlier, I am giving two different types of arguments,I could not define branching alternative arguments in its constructor, because Flash didn't provide constructor overiding like java classes. So, I took this way. Inside I am bifurcating the Argument Processing logic.You can define it in another way.

[as]var line1Args:Array=new Array(pntPoint1,2,-100);
var my_Line1:Line2D=new Line2D(line1Args);

Both will be same. In general second method called as LineVector method, as it is using vx and vy. A vector has magnitude and direction. Here 2 will be the magnitude and -100 is direction. I took that notation in my Object. By default I am rendering Right Normal(Red Line) and Left Normal(Green Line) also. For all the basic dx/dy and Normal values, I followed mostly Mr.Tonypa's vector based animation tutorials for all these Linevector calculations. I am so thankfull to him for those valuble suggstions as response to my Inquisitive emails..

Through Slider change events I am doing these manipulations by code:

In first slider change event :

my_Line1.p0=new Point(sdr_slide_p0X.value,my_Line1.p0.y);

Upto fourth slider The Syntax is same,except parameter change.But in Fifth Slider change, I changed the command like this:


The last thing is just to convert the slider value, which is a whole number, into radians.Now, we are manpulating the changes by this argument value, just like we are applying a simple property value of that Line2D Object.

About Line2D Object:functions

About Line2D Object:functions

Line2D has so many functions to do. It has to update all of its relative values itself with change in each of its properties through set/get functions. In addition to these, it has to return dot product, cross product between two lines. More importantly, It has to tell us whether a line is intersecting with other line, and if they were intersecting, it has to return the Intersection details for us.

Above sample shows some important static functions of the Line2D Object. They are static functions,because I want to relate all the Lines and points on the stage as we can find the orientation details of them in a mutual understanding. I want to maintain a Relational Integrity (which is the  concept in building database tables) for all those points and lines on the Stage. As in the first example, if you want to know the details of one line, it's p0,p1,vx,vy,p1, length and Angle are enough. When You want to know about relationships between two lines or a line and a point, the complexity will be higher. If you are comparing two lines, mathematically calculating dot product and   cross product. And for Visual Orientation, you want to know whether they are parellel or not. If they are not parellel, we need to get at which Point they will intersect. I am not going too much on dot product and cross product as I  know too little about them. I just Implimented an applicable equation from an online mathematics tutorial. And, I am very much concerned about the Intersection,Bounce and Touch features of the Line, because they are very important for Flash Animation Creators. There, I went deep  delving into these features very clearly.

Generally all the People, who worked on Intersection on web sites (even that math gurus) took it as only a point. But It is not. There is an angle, a point and a ratio - were attached as features for the IntersectionPhenomena. Yes, Intersection is a pheomena and its features are IntersectionAngle: at which angle the two lines are intersecting, a relative angle of projection line with orientation line,IntersectionPoint: at which point the ProjectionLine is Intersecting on OrientationLine, and finally IntersectionRatio: which tells us the status report of the Intersection. If the ratio is greater than 1,the lines are not intersecting now but will intersect in future If we extend one of the line in positive direction furher enough to cover that point. If the ratio is between 0 and 1 the lines are currently intersecting on their segment range. If the ratio is negative value, that is lower than Zero, the lines are in after Intersection completed state, that means, If you extend the one of the lines backward, you can see the intersection on the segment range - that's the total concept behind a simple Intersection!

Now, I will explain you the Second Demo. In the First Box on Top Left Corner, I simply showed two intesectiong lines and their Important data. As they are not parellel,they are intersecting, right! I have explained you about the Intersection already. The second box is again has an Important thing to explain. As I said above, If you want to know about two lines, You are seeing their cross point as an intersection. What if you want to know the relation between a line and a point? The relation is to know where the point will touch the Line segment if we moved the point towards the line in a perpendicular angle.That is the TouchPoint This Touch Phenomena also has three features just like Intersection. But their description differs.TouchAngle is the relative angle between the external Point and the StartPoint(p0) of the Line. TouchPoint is the internal point where the Point touches the LineSegment.TouchRatio is just like that of Intersectration Ratio.You can also know that whether it is on the projection line, if the TouchAngle is zero means, The Point is positioned on the Line Projection. In that case the coordinates of external point and internal point are also same, Right!

The code for the First example(Top Left box) will be Like this:

 [as]var pntPoint1:Point=new Point(70,140);
var pntPoint2:Point=new Point(72,40);
var line1Args:Array=new Array(pntPoint1,pntPoint2);
var my_Line1:Line2D=new Line2D(line1Args);my_Line1.render(graphics,true,0x000000);

var pntPoint3:Point=new Point(50,140);
var pntPoint4:Point=new Point(90,40);
var line2Args:Array=new Array(pntPoint3,pntPoint4);
var my_Line2:Line2D=new Line2D(line2Args);

And for the Display Message I used the functions like Line2D.dotProductN(my_Line1,my_Line2) , Line2D.crossProductN(my_Line1,my_Line2) and Line2D.isParellels(my_Line1,my_Line2).

Code for the Second Box which shows Touch Point :

[as]var pntPoint5:Point=new Point(50,240);
var pntPoint6:Point=new Point(90,160);

var line3Args:Array=new Array(pntPoint5,pntPoint6);
var my_Line3:Line2D=new Line2D(line3Args);
//line defined
//line rendered
var pntPoint7:Point=new Point(stage.stageWidth/2-100,stage.stageHeight/2+70);
var my_Touch_Point:Point=new Point(Line2D.getTouch(my_Line3,pntPoint7).p.x,Line2D.getTouch(my_Line3,pntPoint7).p.y);
//Point defined with red circle
//Touch point depicted with blue circle
[/as] p class="mdl">The Left down Most Box shows the BouncePhenomena. This is the most complicated thing, of all the features of the Line2D object. Please pay attention to understand the concept. I am somewhere feeling that I may confuse you if I explained too much. In the next example, there is a dynamic live Example to undestand its application in real world. For now I took a static show. Here the red color Projection Line is Intersecting the black color Orientation Line and Bouncing as green color Reflection Line. Yes, it is equally comparable to a ray reflecting on a surface into its old medium. To understand the actual phenomena we have to split the projection in two parts.First part is from its StartPoint to IntersectionPoint, and the second part is from the IntersectionPoint to its ClosePoint. The Bouncing Line is not how much it is touching the orientation, but how much it crossed the orientation, Am I Right? The angles are normally following the reflection dynamics;that is the incidence angle and reflecting angle are equal. I think that much explanation is enough about what you are seeing there.

The right side top most box shows another static function of line2D that is getResultantLine. This is simple adding lines. The concept is simply adding the vectors. By this function we can add as many lines as we can and it wll return the final Line2D object. And in the simplistic vector additions it is the value is important. But I have extended it in the return value.The code will be like below:

[as]var pntPoint12:Point=new Point(460,50);
var pntPoint13:Point=new Point(550,150);
//first Line Points
var line7Args:Array=new Array(pntPoint12,pntPoint13);
var my_Line7:Line2D=new Line2D(line7Args);
//created first blue line
var int_new_Close_X:Number=my_Line7.p0.x+(my_Line7.Length*Math.cos((my_Line7.Rotation+30)*(Math.PI/180)));
var int_new_Close_Y:Number=my_Line7.p0.y+(my_Line7.Length*Math.sin((my_Line7.Rotation+30)*(Math.PI/180)));
var my_new_POint:Point=new Point(int_new_Close_X,int_new_Close_Y);
//shifted the p1 of first line 30 degres more
var line8Args:Array=new Array(pntPoint12,my_new_POint);
var my_Line8:Line2D=new Line2D(line8Args);
//created green line
var my_cross_point:Point=new Point(Line2D.getIsect(my_Line7,my_Line8).p.x,Line2D.getIsect(my_Line7,my_Line8).p.y);
//found the Intersection and depicted it
var arr_Lines:Array=new Array(my_Line7,my_Line8);
var obj_Added_Line:Line2D=Line2D.getResultantLine(arr_Lines,my_cross_point);
//projecting the added line from the Intersection Point

My concern as a Programmer is where to start this Added Line. So, I gave another argument start point. Here in this example I am reminding about force lines. When two forces are acting upon an object from different angles, In which dirction the object will move and where it will settles at last? This is the visual answer for that question! Before I am moving to the next sample. There is some thing to say about two public functions of Line2D.they are moveTo and moveBy. In the first basic demo, you tossed with p0 and p1 values.Here with moveTo. I am doing the same thing,but I gave the control to the User Programmer as a public function.

About Line2D Object:Behaviour

About Line2D Object:Behaviour

As I promised you earlier, I am showing a demo how really Line2D behaves and exhibits it's features. I am not going to explain all the known things to you again. just see it and understand. what you need to do is just clicking on start button, that's all. If you want to change the speed, change it before clicking start button. After FINISHED button appears, just click reset button.

When you click the start button,You will observe two things. The black line is moving to sides without changing any of its angle,length etc.I used moveTo with one unit speed incriment in that suggestive enterframe function.


And for the green line I used the other function moveBy.:


And I have created a Line at the bottom of the stage and made it to bounce back when it touches that Line.I am not giving the full code as it is similar to the above static example. Only difference is Projection is moving here in enterframe event. The moveBy is taking the  speed as single argument and It is moving in the same angular direction  in each  cycle of the movement.  I am  reminding you that what you see here is  not a MovieClip Animation.  I gave a render function to this Invisible mathematical object Line2D to make this demo a lesser complicated. In Real applications, We could remove it and It willl work like  Point object. By reading it's values, We can position our display Object at the required  Coordinates. I have added a clone method  to the Line2D object, which is useful for reset functionality. This is very useful when we want to render  earlier unchanged movement pattern after manipulating the basic line for a no of times. You need to simply clone the original object and keep it there. After a series of processing statements for that particular Line2D, You can then assign that clone object's values.

This is all  Line2D can do for us. As an Object wise, It's functionality is very simple. All the functionality I showed above is enough. But, If you see it as a prototype of a CollisionDetectionEngine, we can do wonders with it. Currently, I have followed all the new animation techniques which are showcasing a beautiful potency of 2d and 3D packages. Their basic display and Simple Animation features are nice. But, when we checked for their Collision detection feasibility, they are failing to create an Event based architecture around them. I have followed hitTarget logic, Verlet Integration and others, very carefully. I am very much impressed by their accuracy. But, as you saw those three messages in the final example, as three Event Types, COLLISION_START, COLISION_PROGRESS and COLLISION_OVER states of CollisionEvent, you would agree with me that this Line2D object has achieved 90% of the CollisionEvent. It can do more If we can convert into Line3D by giving Point3Ds as arguments and can insert the z in its dotproduct,crossProduct and perProduct functions, and more importantly we could get the 3 Features Isect,bounce and Touch with 3D orientations, We can redefine the Flash3D world. Currently Flash 3d cannot show intersecting planes, Right? That can be achieved If we Thought of them as individual vertices and Line3Ds. As it seems to me that one Axis3D will run from the bottom most z to top most z and all the objects were described with their touchpoints on the Axis3D without bothering about parent-Child relations.if we change Axis orientation, we can transform them with their RelativeIntegralValues (RTV). Most of the redundant matrix calculations would give way to Simple and direct calculations. Currently I am fully Ignorant about that Line3D implimentation. If anybody enlighten me on that subject of  Math3D, I would Update this Line2D Object in its new Avatar Line3D. Until then, Line2D will serve as a backbone for CollisionDetection in 2D.