AS3 Helper Class – Fence()
We are building an AS3 Helper class to speed up development on Actionscript 3 projects. Feel free to use these methods in your own Helper class, or to share your own methods that you find useful.
Fence()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class Helper { import flash.geom.Point; import flash.geom.Rectangle; /** * This method confines a Point * within a Rectangle. Useful for * games where the player and * enemy characters have to stay * within a boundary (ie the screen!). */ public static function Fence(point:Point, theRect:Rectangle):Point { // Make sure the point // is horizontally within limits if (point.x > theRect.right) { point.x = theRect.right; } else if (point.x < theRect.left) { point.x = theRect.left; } // Make sure the point // is vertically within limits if (point.y < theRect.top) { point.y = theRect.top; } else if (point.y > theRect.bottom) { point.y = theRect.bottom; } return point; } } |
Usage
/* Imagine an Asteroids-style game where you need to confine your spaceship within the boundaries of a movieClip instance called "spaceClip" */ var spaceBoundaries:Rectangle = new Rectangle(spaceClip.x, spaceClip.y, spaceClip.width, spaceClip.height); // Store the outer space boundaries var pos:Point = new Point(spaceship.x, spaceship.y); // Store the ship's co-ordinates var xSpeed:Number = 30; var ySpeed:Number = 50; // Set thrusters to "go!" pos.offset(xSpeed, ySpeed); // add the xSpeed/ySpeed to the ship's current position pos = Helper.Fence(pos, spaceBoundaries); // make sure the ship doesn't escape outer space! spaceship.x = pos.x; spaceship.y = pos.y; // position the ship on the screen
Comments
Keeping game characters and objects from leaving the play field is one of those stock-standard things you do in many, many different games – from keeping the pigs inside the sty, to keeping the ball inside the tennis court, to keeping the whatever inside the viewable screen limits. We’re sure to get a lot of mileage from the Fence() method in our future projects.
For more AS3 Helper Classses and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.
Popularity: 2% [?]




Email This Post