AS3 - zoom gesture get zoom direction? - actionscript-3

I've been searching for a way to do what seems like a very simple task.
I have a mousewheel zoom function which works perfectly because the delta value is reset to 0 after each function.
The zoom gesture it seems is not so simple?
My issue is that I'm trying to create a dynamic scale limit (max zoom will be different for each level). and the zoom is getting stuck at the max scale that I'm setting and can't be zoomed out. I'm trying to use the e.scaleX property to identify the direction so that you can zoom out, but it's not working properly.
Thanks for any help!
the code:
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_ZOOM , onZoom);
function onZoom (e:TransformGestureEvent):void{
var zoomAmountGesture:Number = 0;
zoomAmountGesture = e.scaleX;
if (zoomAmountGesture <= 0){
container.scaleX *= e.scaleX;
container.scaleY *= e.scaleY;
if (container.scaleX < 1){
container.scaleX = 1;
container.scaleY = 1
}
}
if (zoomAmountGesture > 0){
container.scaleX *= e.scaleX;
container.scaleY *= e.scaleY;
if(4* BlockSize * container.scaleX > StageWidth){
trace("zoom too big");
var newBlockScale:Number = StageWidth / 3;
var newBoardScale:Number = newBlockScale / BlockSize;
trace("newBoardScale = " + newBoardScale);
container.scaleX = newBoardScale;
container.scaleY = newBoardScale;
}
}
}

I had a quick read of TransformGestureEvent.
The next block has no meaning, because the event scaleX and scaleY properties are 1-based:
if (zoomAmountGesture <= 0){
Then, you should probably start with the following:
function onZoom (e:TransformGestureEvent):void
{
var aScale:Number = container.scaleX * e.scaleX;
if (aScale < 1) aScale = 1;
if (aScale > PredefinedMaxScale) aScale = PredefinedMaxScale;
container.scaleX = aScale;
container.scaleY = aScale;
}

Related

AS3 Constrain Object while Zooming/Panning with GestureEvent / MouseEvent

What I want to do is to keep my MovieClip (which is bigger than the viewport) from having its borders visible. Just like many apps do, e.g. Clash of Clans.
This way if you zoom in and zoom out or pan you will never see the stage under it.
If I was only to pan and not zoom it would be easy because I just had to calculate if my MC rectangle is within my stage and if yes i would just:
mc.x = 0 + mc.width / 2;
//or
mc.x = stage.StageWidth - (mc.width/2);
//or .... The same for y
Now the big problem is when I also zoom! And every time I come up with some code it doesn't work well. There are many examples for zooming via GestureEvent on the web but none of them keeps the MC constrained so you don't see the stage under it.
Can someone please provide an example for me. Lets say the stage is 480x720 and the mc is 1080x720!
You gotta pan and zoom while always covering the stage and the scale of mc will remain within 1-1.5.
Here is my current code:
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
stage.addEventListener(MouseEvent.CLICK, gotoBox);
var isInBox: Boolean = false;
table.x = 203.1;
table.y = 360;
table.scaleX = 1;
table.scaleY = 1;
var mouseTimer: Timer;
function onPan(event: TransformGestureEvent): void
{
if (!isInBox)
{
if (event.phase == GesturePhase.BEGIN)
{
stage.removeEventListener(MouseEvent.CLICK, gotoBox);
trace("noClick");
}
table.x += event.offsetX;
table.y += event.offsetY;
if (table.x > (table.width / 2))
{
table.x = table.width / 2;
}
if (table.x < stage.stageWidth - (table.width / 2))
{
table.x = stage.stageWidth - (table.width / 2)
}
if (table.y > (table.height / 2))
{
table.y = table.height / 2;
}
if (table.y < stage.stageHeight - (table.height / 2))
{
table.y = stage.stageHeight - (table.height / 2)
}
if (event.phase == GesturePhase.END)
{
if (mouseTimer !== null)
{
if (mouseTimer.running)
{
mouseTimer.stop();
mouseTimer.removeEventListener(TimerEvent.TIMER, enableClick);
}
}
mouseTimer = new Timer(250);
mouseTimer.addEventListener(TimerEvent.TIMER, enableClick);
mouseTimer.start();
trace("start");
}
}
}
function enableClick(e: TimerEvent)
{
mouseTimer.stop();
trace("stop");
mouseTimer.removeEventListener(TimerEvent.TIMER, enableClick);
stage.addEventListener(MouseEvent.CLICK, gotoBox);
trace("nowClick");
}
function gotoBox(e: MouseEvent)
{
// here it goes to another frame
}
I cannot add the zooming function because its a total disaster; I used something similar to the function onZoom in this link FlashAndMath
Because I needed to zoom in on a point and out from it, and that is the main issue as I have to move my mc around to make that point in the center WHILE I GOTTA MOVE IT TO MAKE MY WHOLE MC IN A CERTAIN BOUNDARY TO COVER THE STAGE! These too movements act against each other. If this last part is not clear ask me to explain more please:)
After having the right answer from LDMS I updated this question to avoid chat-discussions:)
All you need to do, is whenever you move or scale the object, check to make sure it's not going out of bounds.
So if you made a function called forceBounds, just call it anytime you scale or change the x/y:
function forceBounds():void {
//figure out the bounds to constrain to
//the x, should be the farthest left it can go without the edge being seen on the right. To get this value just subtract the smaller width (stage) from the larger width (mc) - this should be a negative number
var bounds:Rectangle = (stage.stageWidth - mc.width, stage.stageHeight - mc.height, mc.width - stage.stageWidth, mc.height - stage.stageHeight);
if (mc.x > bounds.x + bounds.width) {
mc.x = bounds.x + bounds.width;
}
else if (mc.x < bounds.x) {
mc.x= bounds.x;
}
if (mc.y > bounds.y + bounds.height) {
mc.y = bounds.y + bounds.height;
}
else if (mc.y < bounds.y) {
mc.y = bounds.y;
}
}
Here is a full example I made in FlashPro: (with an object on the the stage with an instance name of mc that is bigger than the stage bounds.
Zoom code taken from FlashAndMath.com
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.events.TransformGestureEvent;
import fl.motion.MatrixTransformer;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.events.GesturePhase;
Multitouch.inputMode = MultitouchInputMode.GESTURE;
stage.addEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
stage.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
forceBounds();
function onPan(e:TransformGestureEvent):void {
trace("PAN");
if(e.phase == GesturePhase.BEGIN){
stage.removeEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
}
//localToGlobal is a helper method that converts a point to global coordinates
var p:Point = DisplayObject(e.target).localToGlobal(new Point(e.offsetX, e.offsetY));
//conversely, global to local does the opposite
p = mc.globalToLocal(p);
mc.x = p.x;
mc.y = p.y;
forceBounds();
if(e.phase == GesturePhase.END){
stage.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
}
}
function onZoom(event:TransformGestureEvent):void {
trace("ZOOM");
var container:MovieClip = mc;
var locX:Number=event.localX;
var locY:Number=event.localY;
var stX:Number=event.stageX;
var stY:Number=event.stageY;
var prevScale:Number=container.scaleX;
var mat:Matrix;
var externalPoint=new Point(stX,stY);
var internalPoint=new Point(locX,locY);
container.scaleX *= (event.scaleX + event.scaleY) * .5;
if(event.scaleX > 1 && container.scaleX > 6){
container.scaleX=prevScale;
}
if(event.scaleY > 1 && container.scaleY > 6){
container.scaleX=prevScale;
}
if(event.scaleX < 1 && container.scaleX < 0.8){
container.scaleX=prevScale;
}
if(event.scaleY < 1 && container.scaleY < 0.8){
container.scaleX=prevScale;
}
if(container.scaleX < 1) container.scaleX = 1;
if(container.scaleX > 1.5) container.scaleX = 1.5;
container.scaleY = container.scaleX;
mat=container.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalPoint,externalPoint);
container.transform.matrix=mat;
forceBounds();
}
function forceBounds():void {
//figure out the bounds to constrain to
//the x, should be the farthest left it can go without the edge being seen on the right. To get this value just subtract the smaller width (stage) from the larger width (mc) - this should be a negative number
var bounds:Rectangle = new Rectangle(stage.stageWidth - mc.width, stage.stageHeight - mc.height, mc.width - stage.stageWidth, mc.height - stage.stageHeight);
if (mc.x > bounds.x + bounds.width) {
mc.x = bounds.x + bounds.width;
}
else if (mc.x < bounds.x) {
mc.x= bounds.x;
}
if (mc.y > bounds.y + bounds.height) {
mc.y = bounds.y + bounds.height;
}
else if (mc.y < bounds.y) {
mc.y = bounds.y;
}
}

AS3 Smooth Jumping

I would like to know how to make a smooth jump in my game. Its a 2D game and the code is really simple but I would want to know how to make it better for it to slow down when it gets to the max height and then smooth drop.
This is all I have for jumping:
Player.y -= 50;
Your best bet would be to use a physics engine (Box2d etc). If you don't want the overhead of one though (if the only thing you'd use it for is jumping and not collisions) then you just need to add some friction to your logic.
var friction :Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity :Number = 50; //how much to move every increment, reset every jump to default value
var direction :int = -1; //reset this to -1 every time the jump starts
function jumpLoop(){ //lets assume this is running every frame while jumping
player.y += velocity * direction; //take the current velocity, and apply it in the current direction
if(direction < 0){
velocity *= friction; //reduce velocity as player ascends
}else{
velocity *= 1 + (1 - friction); //increase velocity now that player is falling
}
if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
if(player.y > stage.stageHeight - player.height){ //stage.stageheight being wherever your floor is
player.y = stage.stageHeight - player.height; //put player on the floor exactly
//jump is over, stop the jumpLoop
}
}
Copy/paste the following code... jump() can be replaced by jump2() (without bouncing effect). The jumping will be produced by the space bar:
const FA:Number = .99; // air resistance
const CR_BM:Number = .8; // bouncing coefficient
const µ:Number = .03; // floor friction
const LB:int = stage.stageHeight; // floor (bottom limit)
const G:int = 2.5; // gravity
const R:int = 50;
var ball:MovieClip = new MovieClip();
this.addChild(ball);
var ba:* = ball.graphics;
ba.beginFill(0xFFCC00);
ba.lineStyle(0, 0x666666);
ba.drawCircle(0, 0, R);
ba.endFill();
ball.vx = 2;
ball.vy = -30;
ball.r = R;
ball.x = 100;
ball.y = LB - R;
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
function myKeyDown(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.SPACE) {
ball.vy = -30;
addEventListener(Event.ENTER_FRAME, jump);
}
}
function jump(e:Event):void {
ball.vy = ball.vy + G;
ball.vx *= FA;
ball.vy *= FA;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y > LB - ball.r) {
ball.y = LB - ball.r;
ball.vy = -1 * ball.vy * CR_BM;
ball.vx += ball.vx * - µ;
}
}
/*
function jump2(e:Event):void {
ball.vy = ball.vy + G;
ball.vx *= FA;
ball.vy *= FA;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y > LB - ball.r) {
ball.y = LB - ball.r;
}
}
*/

Converting complicated trigonometry from AS2 to AS3

I'm trying to make a game, following this tutorial.
The issue comes from the fact that I am using ActionScript 3.0 whereas the tutorial was written using ActionScript 2.0.
Regarding the sight of the enemy, I have turned this code:
onClipEvent (enterFrame) {
dist_x = _root.hero._x-_x;
dist_y = _root.hero._y-_y;
dist = Math.sqrt(dist_x*dist_x+dist_y*dist_y);
angle = Math.atan(dist_y/dist_x)/(Math.PI/180);
if (dist_x<0) {
angle += 180;
}
if (dist_x>=0 && dist_y<0) {
angle += 360;
}
wall_collision = 0;
for (x=1; x<=dist; x++) {
point_x = _x+x*Math.cos(angle*Math.PI/180);
point_y = _y+x*Math.sin(angle*Math.PI/180);
if (_root.wall.hitTest(point_x, point_y, true)) {
wall_collision = 100;
break;
}
}
_root.line._x = _x;
_root.line._y = _y;
_root.line._rotation = angle;
_root.line._alpha = 100-wall_collision;
}
Into that:
// calculate rotation based on target
_dx = this.x - _root.hero.x;
_dy = this.y - _root.hero.y;
// which way to rotate
_rotateTo = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (_rotateTo > barrel.rotation + 90) _rotateTo -= 360;
if (_rotateTo < barrel.rotation - 90) _rotateTo += 360;
// ease rotation
_trueRotation = (_rotateTo - barrel.rotation) / _rotateSpeedMax;
// update rotation
barrel.rotation += _trueRotation;
wall_collision = 0;
OuterLoop: for (var xi=1; xi<=_dx; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_rotateTo);
var point_y:Number = this.y + xi*Math.sin(_rotateTo);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation += _trueRotation;
_root.sight.alpha = 100 - wall_collision;
But the it does not work.
The rotation do work fine, but the whole "alpha = 0 if player is behind a wall" does not work.
Please help me resolving the issue.
Try the following:
// calculate rotation based on target
_dx = _root.hero.x-this.x;
_dy = _root.hero.y-this.y;
// The full distance is missing from your AS3 code
_dist = Math.sqrt(_dx*_dx+_dy*_dy);
// Return the old good approach for finding angle
angle = Math.atan(_dy/_dx)/(Math.PI/180);
if (_dx<0) {
_angle += 180;
}
if (_dx>=0 && _dy<0) {
_angle += 360;
}
wall_collision = 0;
OuterLoop: for (var xi=1; xi<=_dist; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_angle*Math.PI/180);
var point_y:Number = this.y + xi*Math.sin(_angle*Math.PI/180);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation = _angle;
// Alpha changed from [0, 100] scale to [0, 1] scale.
_root.sight.alpha = (100 - wall_collision) * 0.01;
Information on alpha in ActionScript 3.0.
As per AS3 reference, alpha is from 0 to 1, not 0 to 100. That would suggest
`_root.sight.alpha = (100 - wall_collision)/100.0´
might work.
Can You try the following code. I have no prev exp with flash, but seems like You missed something.
The iterator xi should take values in range of distance, not only by one axis dx.
// calculate rotation based on target
_dx = this.x - _root.hero.x;
_dy = this.y - _root.hero.y;
// the iteration is by distance in original article mentioned so
// keep dist
//=================================
_dist = Math.sqrt(_dx*_dx+_dy*_dy);
// which way to rotate
_rotateTo = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (_rotateTo > barrel.rotation + 90) _rotateTo -= 360;
if (_rotateTo < barrel.rotation - 90) _rotateTo += 360;
// ease rotation
_trueRotation = (_rotateTo - barrel.rotation) / _rotateSpeedMax;
// update rotation
barrel.rotation += _trueRotation;
wall_collision = 0;
// xi iterations are to a distance
//== =======
OuterLoop: for (var xi=1; xi<=_dist; xi++)
{
var point_x:Number = this.x + xi*Math.cos(_rotateTo);
var point_y:Number = this.y + xi*Math.sin(_rotateTo);
if(_root.wall.hitTestPoint(point_x, point_y, true))
{
trace("HIT");
wall_collision = 100;
break OuterLoop;
}
}
_root.sight.x = this.x;
_root.sight.y = this.y;
_root.sight.rotation += _trueRotation;
// EDITED AFTER OTHERS SOLVED
// was
//_root.sight.alpha = 100 - wall_collision;
// should be:
// Alpha changed from [0, 100] scale to [0, 1] scale.
_root.sight.alpha = (100 - wall_collision) * 0.01;
// END OF SOLUTION
There is only slight modification to Your original code, marked by preceding //=====
EDIT:
And the winner is transparency range. Still, I do recommend to iterate to a distance, not to _dx.

How do I resize an object in actionscript 3 without changing the hitbox?

When I resize a button in actionscript 3 the hitbox changes to the text instead of the square in my assignment example:
http://www.datafilehost.com/download-5ff20e2c.html
Video Explaining Issue: http://sdrv.ms/YcnjYV
Here is the code:
import flash.events.MouseEvent;
trace("Stage(X,Y):" + stage.stageWidth + "X" + stage.stageHeight);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousePosition);
clickMe.addEventListener(MouseEvent.CLICK, handleClicks);
function mousePosition(event:MouseEvent) {
if(clickMe.mouseX >= 0 && clickMe.mouseX <= clickMe.width && clickMe.mouseY >= 0 && clickMe.mouseY <= clickMe.height)
{
do
{
var newX = Math.floor(Math.random()*stage.stageWidth);
var newY = Math.floor(Math.random()*stage.stageHeight)
}while(newX >= stage.stageWidth - clickMe.width || newY >= stage.stageHeight - clickMe.height)
clickMe.x = newX;
clickMe.y = newY;
if(clickMe.width > 50)
{
clickMe.width=clickMe.width - 5;
clickMe.height = clickMe.width - 5;
}
}
}
function handleClicks(event:MouseEvent)
{
trace("Button Clicked!");
}
How can I get the hitbox to stay the same when resizing an object?
this seems like a better and cleaner approach to what you are doing (assuming you move the clickMe clip to a random position and shrink it by 5px)
import flash.events.MouseEvent;
clickMe.addEventListener(MouseEvent.ROLL_OVER, moveSquare);
function moveSquare(e:MouseEvent):void
{
var newX = Math.floor(Math.random()*stage.stageWidth);
var newY = Math.floor(Math.random()*stage.stageHeight);
clickMe.x = newX;
clickMe.y = newY;
clickMe.width = clickMe.width - 5;
clickMe.height = clickMe.height - 5;
}
Changing of button size affects on mouseX/mouseY value inside it. So dont rely on it and just use checking based on button position and size.
if(mouseX >= clickMe.x && mouseX <= clickMe.x+clickMe.width && mouseY >= clickMe.y && mouseY <= clickMe.y+clickMe.height)

Make a boundary in flash with as3

I have this code that generates circles and makes them float within the boundaries of the stage. Although it stays in the stage it also has some give and let's the circles push through a small amount which I like.
Is it possible to do this but with a custom shape and have the circles confined inside this shape?
Here is the code I have:
//number of balls
var numBalls:uint = 200;
var defaultBallSize:uint = 8;
var colors:Array = [0x79B718, 0x2D91A8, 0xB019BC, 0xF98715, 0xDB1616];
//init
makeDots();
function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum<numBalls; ballNum++){
var c1:Number = randomColor();
var c2:Number = randomColor();
//create ball
var thisBall:MovieClip = new MovieClip();
thisBall.graphics.beginFill(c1);
//thisBall.graphics.lineStyle(defaultBallSize, 0);
thisBall.graphics.drawCircle(defaultBallSize, defaultBallSize, defaultBallSize);
thisBall.graphics.endFill();
addChild(thisBall);
//coordinates
thisBall.x = Math.random() * stage.stageWidth;
thisBall.y = Math.random() * stage.stageHeight;
//percieved depth
thisBall.ballNum = ballNum;
thisBall.depth = ballNum/numBalls;
thisBall.scaleY = thisBall.scaleX =
////thisBall.alpha =
ballNum/numBalls;
//velocity
thisBall.vx = 0;
thisBall.vy = 0;
thisBall.vz = 0;
//ball animation
thisBall.addEventListener(Event.ENTER_FRAME, animateBall);
}
}
var dampen:Number = 0.90;
var maxScale:Number = 1.3;
var minScale:Number = .3;
var maxAlpha:Number = 1.3;
var minAlpha:Number = .3;
function animateBall(e:Event):void{
var thisBall:Object = e.target;
//apply randomness to velocity
thisBall.vx += Math.random() * 0.2 - 0.1;
thisBall.vy += Math.random() * 0.2 - 0.1;
thisBall.vz += Math.random() * 0.002 - 0.001;
thisBall.x += thisBall.vx;
thisBall.y += thisBall.vy;
//thisBall.scaleX = thisBall.scaleY += thisBall.vz;
//thisBall.alpha += thisBall.vz;
thisBall.vx *= dampen;
thisBall.vy *= dampen;
thisBall.vz *= dampen;
if(thisBall.x > stage.stageWidth) {
thisBall.x = 0 - thisBall.width;
}
else if(thisBall.x < 0 - thisBall.width) {
thisBall.x = stage.stageWidth;
}
if(thisBall.y > stage.stageHeight) {
thisBall.y = 0 - thisBall.height;
}
else if(thisBall.y < 0 - thisBall.height) {
thisBall.y = stage.stageHeight;
}
if (thisBall.scaleX > maxScale){
thisBall.scaleX = thisBall.scaleY = maxScale;
}
else if (thisBall.scaleX < minScale){
thisBall.scaleX = thisBall.scaleY = minScale;
}
if (thisBall.alpha > maxAlpha){
thisBall.alpha = maxAlpha;
}
else if (thisBall.alpha < minAlpha){
thisBall.alpha = minAlpha;
}
}
function randomColor():uint
{
return colors[int(Math.random()*colors.length)];
}
Code credit:
Originally from here: Circle Cube
Additional help here: Random colour within a list of pre-defined colours
Yes, you can. What is happening is that when each circle moves, it is checked to see if it is within the stage bounds on the x and y axis and is 'corrected' if it goes out. You can modify that part of the code that determines this to check if a circle is within your custom shape or not.
The complexity of this will depend on your custom shape as well as the method to go about detecting if a circle/object is within your custom shape.
The 'easiest custom shape' you could try would be a rectangle or square, since the stage is already a big rectangle. To start this, look through your given code to find the lines of code that limit the x and y position of the stage dimensions and change them to the dimensions of your custom rectangle/square. You may have to add in position offsets if your custom shape rectangle/square does not originate from 0, 0 like the stage. I suggest factoring this part out (which is actually basic collision detection) into a method if you want to experiment with other shapes.
Edit
I edited my answer to include the original code reworked to use a random square as the custom shape -the easiest shape to try as mentioned in my original answer. Hopefully you can compare the two and see the changes I made to try and figure out the logic behind it.
For a circle, or any other totally random shape, it would be a bit more difficult, but same idea/concept.
//number of balls
var numBalls:uint = 200;
var defaultBallSize:uint = 8;
var colors:Array = [0x79B718, 0x2D91A8, 0xB019BC, 0xF98715, 0xDB1616];
// new custom shape bounds, a square that is 200, 200 px and is at 175, 100 on the stage
var customSquare:Rectangle = new Rectangle(175, 100, 200, 200);
//init
makeDots();
function makeDots():void {
//create desired number of balls
for (var ballNum:uint=0; ballNum < numBalls; ballNum++){
var c1:Number = randomColor();
var c2:Number = randomColor();
//create ball
var thisBall:MovieClip = new MovieClip();
thisBall.graphics.beginFill(c1);
//thisBall.graphics.lineStyle(defaultBallSize, 0);
thisBall.graphics.drawCircle(defaultBallSize, defaultBallSize, defaultBallSize);
thisBall.graphics.endFill();
addChild(thisBall);
//coordinates - this part of the code is setting the initial positions of the circles based on the stage size
//thisBall.x = Math.random() * stage.stageWidth;
//thisBall.y = Math.random() * stage.stageHeight;
//
// changed so they use the "customSquare" rectangle instead, note that the custom shape has an x and y pos now that doesn't start at 0 (unlike the stage)
thisBall.x = (Math.random() * customSquare.width) + customSquare.x;
thisBall.y = (Math.random() * customSquare.height) + customSquare.y;
//percieved depth
thisBall.ballNum = ballNum;
thisBall.depth = ballNum / numBalls;
thisBall.scaleY = thisBall.scaleX = ballNum / numBalls;
//velocity
thisBall.vx = 0;
thisBall.vy = 0;
thisBall.vz = 0;
//ball animation
thisBall.addEventListener(Event.ENTER_FRAME, animateBall);
}
}
var dampen:Number = 0.90;
var maxScale:Number = 1.3;
var minScale:Number = .3;
var maxAlpha:Number = 1.3;
var minAlpha:Number = 0.3;
function animateBall(e:Event):void{
var thisBall:Object = e.target;
//apply randomness to velocity
/*thisBall.vx += Math.random() * 0.2 - 0.1;
thisBall.vy += Math.random() * 0.2 - 0.1;
thisBall.vz += Math.random() * 0.002 - 0.001;*/
// increased velocity ranges to add more speed to see the effects easier
thisBall.vx += Math.random() * 1.2 - 0.6;
thisBall.vy += Math.random() * 1.2 - 0.6;
thisBall.vz += Math.random() * 0.012 - 0.006;
thisBall.x += thisBall.vx;
thisBall.y += thisBall.vy;
//thisBall.scaleX = thisBall.scaleY += thisBall.vz;
//thisBall.alpha += thisBall.vz;
thisBall.vx *= dampen;
thisBall.vy *= dampen;
thisBall.vz *= dampen;
// =====================================================================================================================================
// this part of the code is determining if each ball is going outside of the bounds of the stage and repositioning them if they are
// this part is the 'collision detection', changed to use the bounds of the "customSquare" rectangle instead
//
// this part is detecting the position going out of bounds along the X axis
/*if(thisBall.x > stage.stageWidth) {
thisBall.x = 0 - thisBall.width;
} else if(thisBall.x < 0 - thisBall.width) {
thisBall.x = stage.stageWidth;
}*/
if(thisBall.x > (customSquare.width + customSquare.x)) {
thisBall.x = customSquare.x - thisBall.width;
} else if(thisBall.x < customSquare.x - thisBall.width) {
thisBall.x = customSquare.width + customSquare.x;
}
// this part is detecting the position going out of bounds along the Y axis
/*if(thisBall.y > stage.stageHeight) {
thisBall.y = 0 - thisBall.height;
} else if(thisBall.y < 0 - thisBall.height) {
thisBall.y = stage.stageHeight;
}*/
if(thisBall.y > (customSquare.height + customSquare.y)) {
thisBall.y = customSquare.y - thisBall.height;
} else if(thisBall.y < customSquare.y - thisBall.height) {
thisBall.y = customSquare.height + customSquare.y;
}
// =====================================================================================================================================
if (thisBall.scaleX > maxScale){
thisBall.scaleX = thisBall.scaleY = maxScale;
} else if (thisBall.scaleX < minScale){
thisBall.scaleX = thisBall.scaleY = minScale;
}
if (thisBall.alpha > maxAlpha){
thisBall.alpha = maxAlpha;
} else if (thisBall.alpha < minAlpha){
thisBall.alpha = minAlpha;
}
}
function randomColor():uint{ return colors[int(Math.random()*colors.length)]; }
Assuming all you are asking is for a border around the confined area, You could do something like:
var container:MovieClip = new MovieClip;
container.graphics.lineStyle(1,0,1);
container.graphics.drawRect(0, 0, container.width, container.height);
container.graphics.endFill();
addChild(container);
And Replace :
addChild(thisBall);
With :
container.addChild(thisBall);
From animating in flash I can tell you the flash-way of doing something like this is through layer masks. This should is possible in code too. Something loosely like this:
addChild(thisBall);
var layermask:Shape=new Shape();
addChild(layermask);
thisBall.mask=maskingShape;