02.02.2013 Views

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Flash</strong> <strong>MX</strong> <strong>2004</strong> <strong>Games</strong><br />

the distance between two locations. Finally we convert the ‘point’ in<strong>to</strong> a string using the ‘dump’<br />

function defined in lines 16 <strong>to</strong> 18.<br />

1 class point{<br />

2 var x:Number = 0;<br />

3 var y:Number = 0;<br />

4<br />

5 function point(xx:Number, yy:Number){<br />

6 x = xx;<br />

7 y = yy;<br />

8 }<br />

9<br />

10 function distanceTo(pt:point):Number{<br />

11 var dx:Number = x - pt.x;<br />

12 var dy:Number = y - pt.y;<br />

13 return Math.sqrt(dx * dx + dy * dy);<br />

14 }<br />

15<br />

16 function dump(){<br />

17 return ("(" + x + ", " + y + ")");<br />

18 }<br />

19 }<br />

Listing 10.2<br />

Listing 10.3 shows how we use the ‘point’ class. Line 1 creates a new point with the x value<br />

set <strong>to</strong> 10 and the y value set <strong>to</strong> 10. By using the new keyword <strong>Flash</strong> knows <strong>to</strong> try <strong>to</strong> find a class<br />

definition of point in the current folder. It finds the definition in the <strong>ActionScript</strong> file ‘point.as’.<br />

<strong>Flash</strong> then looks in the class for the construc<strong>to</strong>r function, simply a function with the same name<br />

as the class, and uses the parameters passed <strong>to</strong> initialize the class. Lines 3 and 4 show how the<br />

output from the ‘dump’ function can be used within a ‘trace’ statement and the output from the<br />

‘distanceTo’ is also used.<br />

1 pt1 = new point(10, 10);<br />

2 pt2 = new point(100, 50);<br />

3 trace("Distance from " + pt1.dump() + " <strong>to</strong> " +<br />

4 pt2.dump() + " is " + pt1.distanceTo(pt2));<br />

Listing 10.3<br />

In a complex project there could be several programmers working on different <strong>ActionScript</strong><br />

class files. Another very useful feature of classes is their ability <strong>to</strong> inherit the characteristics of an<br />

existing class. Listing 10.4 shows the ‘vec<strong>to</strong>r’ class. A vec<strong>to</strong>r has the same data set as a point; namely,<br />

in the case of a two-dimensional vec<strong>to</strong>r, it has just two numeric values, but instead of representing<br />

146

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!