Drag and Rotate MC in Actionscript 3 - actionscript-3

I am trying to take a movieclip inside of an AS3 file and make it rotate smoothly when someone clicks and drags it. I know my code is close but right now instead of dragging, it moves a fixed distance on click. You can see the sample here: http://server.iconixinc.com/drag/
and here is my code
const TO_DEGREE:Number = 180/Math.PI;
addEventListener(MouseEvent.MOUSE_DOWN, startRotate, true);
addEventListener(MouseEvent.MOUSE_UP, stopRotate, true);
var maxRotSpeed:Number = .1;
var rotScale:Number = 0.2;
function startRotate(e:MouseEvent):void
{
var dx:int = stage.mouseX - myMc.x;
var dy:int = stage.mouseY - myMc.y;
var rot:Number = Math.atan2(dy, dx) * TO_DEGREE;
var drot = rot - myMc.rotation;
if(drot < -180) drot += 360;
if(drot > 180) drot -= 360;
drot *= rotScale;
myMc.rotation += drot;
}
function stopRotate(e:MouseEvent) {
myMc.stopDrag();
}
Any thoughts on what I might be doing wrong?

You aren't actually using the drag and drop features of AS3, so you don't need the call to stopDrag. You're actually very close, you just want to move your code into a move listener:
const TO_DEGREE:Number = 180/Math.PI;
addEventListener(MouseEvent.MOUSE_DOWN, startRotate, true);
addEventListener(MouseEvent.MOUSE_UP, stopRotate, true);
var maxRotSpeed:Number = .1;
var rotScale:Number = 0.2;
function startRotate(e:MouseEvent):void
{
// you want the calculation to occur whenever the mouse moves,
// not just when the mouse button is clicked
addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}
function onMouseMove(e:MouseEvent):void {
var dx:int = stage.mouseX - myMc.x;
var dy:int = stage.mouseY - myMc.y;
var rot:Number = Math.atan2(dy, dx) * TO_DEGREE;
var drot = rot - myMc.rotation;
if(drot < -180) drot += 360;
if(drot > 180) drot -= 360;
drot *= rotScale;
myMc.rotation += drot;
}
function stopRotate(e:MouseEvent) {
// instead of calling stopDrag, you simply remove the move listener
removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
}

Related

Actionscript 3.0 Mouse trail snake game logic

I am developing a game in actionscript 3.0 (adobe flash) similar to this https://www.tvokids.com/preschool/games/caterpillar-count. I have the code for dragging the head of the snake in the direction of the mouse. However, I do not know how do I add the body of the snake and make it follow the path of the head. Following is my code to drag movieclip in the direction of the mouse :
var _isActive = true;
var _moveSpeedMax:Number = 1000;
var _rotateSpeedMax:Number = 15;
var _decay:Number = .98;
var _destinationX:int = 150;
var _destinationY:int = 150;
var _dx:Number = 0;
var _dy:Number = 0;
var _vx:Number = 0;
var _vy:Number = 0;
var _trueRotation:Number = 0;
var _player;
var i;
createPlayer();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function createPlayer():void{
_player = new head();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 2;
stage.addChild(_player);
}
function onDown(e:MouseEvent):void{
_isActive = true;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onMove(e:MouseEvent):void{
updatePosition(_player);
updateRotation(_player);
}
function onUp(e:MouseEvent):void{
_isActive = false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
}
function updatePosition(mc):void
{
// check if mouse is down
if (_isActive)
{
// update destination
_destinationX = stage.mouseX;
_destinationY = stage.mouseY;
// update velocity
_vx += (_destinationX - mc.x) / _moveSpeedMax;
_vy += (_destinationY - mc.y) / _moveSpeedMax;
}
else
{
// when mouse is not down, update velocity half of normal speed
_vx += (_destinationX - mc.x) / _moveSpeedMax * .25;
_vy += (_destinationY - mc.y) / _moveSpeedMax * .25;
}
// apply decay (drag)
_vx *= _decay;
_vy *= _decay;
// if close to target, slow down turn speed
if (getDistance(_dx, _dy) < 50)
{
_trueRotation *= .5;
}
// update position
mc.x += _vx;
mc.y += _vy;
}
function updateRotation(mc):void
{
// calculate rotation
_dx = mc.x - _destinationX;
_dy = mc.y - _destinationY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > mc.rotation + 180) rotateTo -= 360;
if (rotateTo < mc.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - mc.rotation) / _rotateSpeedMax;
// update rotation
mc.rotation += _trueRotation;
}
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
The script below will not miraculously work on its own, however it has all the logic you need, well-explained. It makes a chain of any length follow its head by certain rules. I used the same principle here many years ago: http://delimiter.ru/games/25-lines/alone.html
// This one will represent the Mouse position.
var Rat:Sprite = new Sprite;
// The ordered list of chain elements.
// It all starts with the Mouse.
var Snake:Array = [Rat];
// Call this one each time you want to
// extend the snake with the piece of tail.
function addTail(aPiece:DisplayObject):void
{
// Get the last snake element.
var lastPiece:DisplayObject = Snake[Snake.length - 1];
// Sync the tail coordinates.
aPiece.x = lastPiece.x;
aPiece.y = lastPiece.y;
// Add the new piece to the snake.
Snake.push(aPiece);
}
// Add the pre-defined head as the first element.
addTail(SnakeHead);
// Now start following the Mouse.
addEventListener(Event.ENTER_FRAME, onFrame);
// Fires every frame and adjusts the whole snake, if needed.
function onFrame(e:Event):void
{
// Sync the attractor point with the Mouse.
Rat.x = mouseX;
Rat.y = mouseY;
// Now lets make each piece follow the previous piece,
// one by one, starting from the head, down to the tail.
for (var i:int = 1; i < Snake.length; i++)
{
followOne(Snake[i - 1], Snake[i]);
}
}
function followOne(A:DisplayObject, B:DisplayObject):void
{
// Think of these values as of vector
// pointing from B position to A position.
var dx:Number = A.x - B.x;
var dy:Number = A.y - B.y;
// Figure out the distance between the given pieces.
var aDist:Number = Math.sqrt(dx * dx + dy * dy);
// Do nothing if pieces are closer than 20 px apart.
// You can change this value to make snake shorter or longer.
if (aDist < 20)
{
return;
}
// This literally means "eat one tenth of the distance
// between me and the previous piece". If you want pieces
// to follow each other with more vigor, reduce this value,
// if you want the whole snake to slither smoothly, increase it.
B.x += dx / 10;
B.y += dy / 10;
// Rotate the B piece so it would look right into A's direction.
// Well, unless your pieces are round and look all the same.
B.rotation = Math.atan2(dy, dx) * 180 / Math.PI;
}

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 How can I constrain an objects movement within the stage?

My object is controlled via mouse movement (for now)... Because of the way it's controlled (object always moves away from cursor), I want to add constraints so that it not only stays within the stage but leaves space between the movement boundaries and the stage edges...
Therefore if the object moves too close to the stage limits, there will be room for the cursor to move it back into the play area.
Currently, I have a rectangle created dynamically within the stage and I was thinking I could constrain movement to within the area of this rectangle, which would leave enough room around the edges... How can I do this?
However, if there's a better/easier way to get the desired results... I'm all ears.
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Shape;
var rectangle:Shape = new Shape;
//initialize "rectangle" shape
rectangle.graphics.beginFill(0xCCCCCC);
//choose colour for fill - black
rectangle.graphics.drawRect(50, 50, 450, 300);
//draw shape
rectangle.graphics.endFill();
//end fill
addChild(rectangle);
//add "rectangle" to stage
var hero:MovieClip = new hero_mc();
//initialize "hero" object - "hero_mc"
hero.x = stage.stageWidth / 2;
hero.y = stage.stageHeight / 2;
//set spawn location, centre stage
addChild(hero);
//add "hero" to stage
function cursorHold(evt:Event):void {
trace("moving");
var dX:Number = hero.x - stage.mouseX;
//get adjacent
var dY:Number = hero.y - stage.mouseY;
//get opposite
var r:Number = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
//get hypotenuse
var angle:Number = Math.acos(dX/r)*180/Math.PI;
//get angle
var radians:Number = deg2rad(angle);
//call conversion function for angle
var speed:Number = 1.5;
//set speed
var xV:Number = Math.cos(radians) * speed;
//get x velocity
var yV:Number = Math.sin(radians) * speed;
//get y velocity
hero.x += xV;
//move hero along new x velocity
if (stage.mouseY > hero.y) {
hero.y -= yV;
} else {
hero.y += yV;
}
//move hero along new y velocity
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI / 180);
//convert degrees to radians
}
stage.addEventListener(Event.ENTER_FRAME, cursorHold, false, 0, true);
Here's an image: https://lh5.googleusercontent.com/lWG8uR9MLK32oHXX26JBiLtBdvmiICFuxOQakQESnBY=w552-h402-no
So, "hero_mc" shouldn't be able to move into the white area but it should still move (scrape against the edges with the mouse movement.
Apologies if the code is a mess... I'm pretty new to ActionScript 3.0. Any tips on cleaning it up a bit would also be more than welcome.
here are some tips for you..
First, I would add a var for the margin to dynamically draw the active area of the stage and then create the rectangle using that, like this -
// margin of stage
var margin:uint = 20;
rectangle.graphics.drawRect(margin, margin, stage.stageWidth-(2*margin), stage.stageHeight-(2*margin));
Then I would also add a var for getting the center of the hero mc like this -
var heroCenter:Number = hero.width * .5;
And finally a var for setting the yV to += or -= and using an if to set it like this -
var posNeg:Number = 0;
if(stage.mouseY > hero.y){
posNeg = -1;
} else {
posNeg = 1;
}
hero.y += yV*posNeg;
Here is the full code. I set it to a speed to 10 to test faster.
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Shape;
// margin of stage
var margin:uint = 20;
var rectangle:Shape = new Shape;
//initialize "rectangle" shape
rectangle.graphics.beginFill(0xCCCCCC);
//choose colour for fill - black
rectangle.graphics.drawRect(margin, margin, stage.stageWidth-(2*margin), stage.stageHeight-(2*margin));
//draw shape
rectangle.graphics.endFill();
//end fill
addChild(rectangle);
//add "rectangle" to stage
var hero:MovieClip = new hero_mc();
//initialize "hero" object - "hero_mc"
// half hero to make sure hero goes completely to edge of stage without going over or under
// best if the hero widht is an even number.
var heroCenter:Number = hero.width * .5;
hero.x = stage.stageWidth / 2;
hero.y = stage.stageHeight / 2;
//set spawn location, centre stage
addChild(hero);
//add "hero" to stage
var posNeg:Number = 0;
function cursorHold(evt:Event):void {
//trace("moving");
var dX:Number = hero.x - stage.mouseX;
//get adjacent
var dY:Number = hero.y - stage.mouseY;
//get opposite
var r:Number = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
//get hypotenuse
var angle:Number = Math.acos(dX/r)*180/Math.PI;
//get angle
var radians:Number = deg2rad(angle);
//call conversion function for angle
var speed:Number = 10;
//set speed
var xV:Number = Math.cos(radians) * speed;
//get x velocity
var yV:Number = Math.sin(radians) * speed;
//get y velocity
hero.x += xV;
if(hero.x < margin + heroCenter){
hero.x = margin + heroCenter;
}
if(hero.x > stage.stageWidth - (margin + heroCenter)){
hero.x = stage.stageWidth - (margin + heroCenter);
}
if(stage.mouseY > hero.y){
posNeg = -1;
} else {
posNeg = 1;
}
hero.y += yV*posNeg;
//move hero along new x velocity
if (hero.y > stage.stageHeight - (margin + heroCenter)) {
hero.y = stage.stageHeight - (margin + heroCenter);
} else if (hero.y < margin + heroCenter) {
hero.y = margin + heroCenter;
}
//move hero along new y velocity
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI / 180);
//convert degrees to radians
}
stage.addEventListener(Event.ENTER_FRAME, cursorHold, false, 0, true);

as3 MOUSE_UP stopDrag() not functioning

I am working on a basic as3 slingshot game which uses startDrag() and stopDrag() to let the user pull an object and fire. when the object is not stretching the "elastic" the MOUSE_UP function works as it should, but when it is below the set points and is stretching the string the MOUSE_UP function is not being called.
vars
var gravity = 0.1;
var angle1:Number = 0;
var angle2:Number = 0;
var radius:Number = 1;
var elasticCoefficient:Number = 0.002;
var released:Boolean = true;
var forced:Boolean = false;
var acc:Object = {x:0 , y:0};
var vel:Object = {x:0 , y:0};
var elastic:MovieClip = new MovieClip();
the ENTER_FRAME code is
function doConstantly(e:Event):void
{
acc.x = 0;
acc.y = gravity;
if(released == true)
{
vel.x += acc.x;
vel.y += acc.y;
ball.x += vel.x;
ball.y += vel.y
}
if(ball.y > stage.stageHeight + 500 || ball.y < -50)
{
resetLevel();
}
elastic.graphics.clear();
elastic.graphics.lineStyle(2, 0xFFF2BD);
if(ball.y > point1.y && ball.x < point2.x)
{
forced = true;
var x1:Number = ball.x - point1.x;
var y1:Number = ball.y - point1.y;
var x2:Number = point2.x - ball.x;
var y2:Number = point2.y - ball.y;
var distance1:Number = Math.sqrt(x1 * x1 + y1 * y1);
var distance2:Number = Math.sqrt(x2 * x2 + y2 * y2);
angle1 = Math.atan2(y1,x1);
angle2 = Math.atan2(y2,x2);
var xOffset:Number = Math.cos(angle1 + Math.PI / 2) * radius;
var yOffset:Number = Math.sin(angle1 + Math.PI / 2) * radius;
var xOffset2:Number = Math.cos(angle2 + Math.PI / 2) * radius;
var yOffset2:Number = Math.sin(angle2 + Math.PI / 2) * radius;
angle1 += Math.sin(radius / distance1);
angle2 += Math.sin(radius / distance2) * -1;
elastic.graphics.moveTo(point1.x, point1.y);
elastic.graphics.lineTo(ball.x+xOffset, ball.y+yOffset);
elastic.graphics.moveTo(point2.x, point2.y);
elastic.graphics.lineTo(ball.x+xOffset2, ball.y+yOffset2);
}
else
{
forced = false;
if(forced == true){trace("forced is true")}
if(forced == false){trace("forced is false")}
elastic.graphics.moveTo(point1.x, point1.y);
elastic.graphics.lineTo(point2.x, point2.y);
}
if (released == true && forced == true)
{
acc.x += distance1 * Math.sin(angle2) * elasticCoefficient;
acc.y += - distance1 * Math.cos(angle1) * elasticCoefficient;
acc.x += distance2 * Math.sin(angle1) * elasticCoefficient;
acc.y += - distance2 * Math.cos(angle2) * elasticCoefficient;
vel.x += acc.x;
vel.y += acc.y;
}
}
and the mouse events
function ballMouseDown(event:MouseEvent)
{
//call function to reset level
resetLevel();
//follow mouse
ball.x = mouseX;
ball.y = mouseY;
ball.startDrag();
//set released to false so that gravity wont affect the ball when clicked
released = false;
}
function ballMouseUp(event:MouseEvent)
{
trace("mouse up function called")
released = true; //gravity will affect the ball when released
ball.stopDrag();
}
Thanks.
Try adding the MOUSE_UP handler to the stage instead - at the moment, you will need to release your mouse while it is over the ball which may not be the case.
Update your MOUSE_DOWN handler to attach the listener to the stage:
function ballMouseDown(e:MouseEvent):void
{
// ...your current code.
stage.addEventListener(MouseEvent.MOUSE_UP, ballMouseUp);
}
And removing the listener when the handler is triggered:
function ballMouseUp(e:MouseEvent):void
{
// ...your current code.
stage.removeEventListener(MouseEvent.MOUSE_UP, ballMouseUp);
}

Physics angular bounce as3

Below is my current code and i am trying to get my ball to bounce off with the proper angle of refraction based on the random angled walls and direction of the ball...My problem is I have only taken a basic physics class and know the equation "angle of incidence = angle of refraction" also, this is my first year in as3 so my coding is rather crude. The angle seems to be off...the problem is with the code "Bullet.hitTestObject(myblockadeHolder[t])" Thanks guys.
stage.addEventListener(Event.ENTER_FRAME,rotate);
var _trueRotation:Number;
var _dx:Number;
var _dy:Number;
function rotate (e:Event){
// calculate rotation based on mouse X & Y
_dx = Turret.x - stage.mouseX;
_dy = Turret.y - stage.mouseY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > Turret.rotation + 180) rotateTo -= 360;
if (rotateTo < Turret.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - Turret.rotation - 90) / 3;
// update rotation
Turret.rotation += _trueRotation;
}
//Turret Rotation
//Create an array to hold multiple sprites
var mySpriteHolder:Array = [];
//Create a counter to keep track of the number of sprites
var lbCounter:int = 0;
//Maximum number of sprites on the canvas
var maxLB:int = 1;
//Keypress Code
stage.addEventListener(MouseEvent.CLICK, dropBullet);
//Function for the mouse event to fire bullet
function dropBullet(evt:MouseEvent):void{
var bcos:Number = Math.cos((Turret.rotation - 90) * Math.PI / 180);
var bsin:Number = Math.sin((Turret.rotation - 90) * Math.PI / 180);
//starting x and y
var startx:int = Turret.x + (70 * bcos);
var starty:int = Turret.y + (70 * bsin);
//calculates where the bullet needs to go by aiming in front of the gun
var endx:int = Turret.x + (100 * bcos);
var endy:int = Turret.y + (100 * bsin);
var Bullet:MovieClip = new bullet();
Bullet.x = startx;
Bullet.y = starty;
Bullet.xspeed = (endx - startx)/5;
Bullet.yspeed = (endy - starty)/5;
mySpriteHolder.push(Bullet);
stage.addChild(Bullet);
//this calls the move down function
stage.addEventListener(Event.ENTER_FRAME,BulletFire);
}
//Function to shoot bullet
var Points:Number = 0;
var Life:Number = 100;
stage.addEventListener(Event.ENTER_FRAME, TextCounter);
function BulletFire(evt:Event):void{
var Bullet:MovieClip;
//Use a for loop to move the Bullets
for(var i:int=mySpriteHolder.length-1; i>=0; i--){
Bullet = mySpriteHolder[i];
//Bounds Collision
if(Bullet.hitTestObject(Up)){
Bullet.yspeed*=-1;
}
if(Bullet.hitTestObject(Lower)){
Bullet.yspeed*=-1;
}
if(Bullet.hitTestObject(Left)){
Bullet.xspeed*=-1;
}
if(Bullet.hitTestObject(Right)){
Bullet.xspeed*=-1;
}
if(Bullet.hitTestObject(Tank)){
stage.removeChild(Bullet);
mySpriteHolder.splice(i,1);
lbCounter --;
Life -= 10;
}
//Blockade Collision
for(var t in myBlockadeHolder){
if(Bullet.hitTestObject(myBlockadeHolder[t])){
_trueRotation*=2
var newAngle = (180 - (_trueRotation) - (smallangle))*-1;
var newXspeed = Math.cos(newAngle);
var newYspeed = Math.sin(newAngle);
Bullet.xspeed = newXspeed+2.5;
Bullet.yspeed = newYspeed+2.5;
}
}
//Target Collision
for(var c in mytargetHolder){
if(Bullet.hitTestObject(mytargetHolder[c])){
stage.removeChild(Bullet);
mySpriteHolder.splice(i,1);
lbCounter --;
Points += 10;
mytargetHolder[c].y = Math.random()*380 + 10;
mytargetHolder[c].x = Math.random()*380 + 10;
while(mytargetHolder[c].hitTestObject(Turret)){
mytargetHolder[c].y = Math.random()*380 + 10;
mytargetHolder[c].x = Math.random()*380 + 10;
}
}
for(var a in mytargetHolder){
for(var s in mytargetHolder){
while(mytargetHolder[a].hitTestObject(mytargetHolder[s])&& a!=s){
mytargetHolder[a].y = Math.random()*380 + 10;
mytargetHolder[a].x = Math.random()*380 + 10;
}
}
for(var g in myBlockadeHolder){
while(mytargetHolder[a].hitTestObject(myBlockadeHolder[g])&& a!=g){
mytargetHolder[a].y = Math.random()*380 + 10;
mytargetHolder[a].x = Math.random()*380 + 10;
}
}
}
}
Bullet.y += Bullet.yspeed;
Bullet.x += Bullet.xspeed;
}
}//Bullet Code
stage.addEventListener(Event.ENTER_FRAME, HealthCheck);
function HealthCheck(e:Event):void{
if(Life<=0){
stage.removeEventListener(MouseEvent.CLICK, dropBullet);
stage.removeEventListener(Event.ENTER_FRAME, BulletFire);
stage.removeEventListener(Event.ENTER_FRAME, droptarget);
stage.removeEventListener(Event.ENTER_FRAME, dropblockade);
}
}//Health Code
//variables for blockade
var myblockadeSprite:Sprite;
//blockade is the linkage name in the library
var blockade:Blockade;
//Create an array to hold multiple sprites
var myBlockadeHolder:Array = new Array();
//Create a counter to keep track of the number of sprites
var LbCounter:int = 0;
//Maximum number of sprites on the canvas
var maxlb:int = 6;
//Keypress Code
stage.addEventListener(Event.ENTER_FRAME, dropblockade);
//Function for the mouse event to fire blockade
function dropblockade(evt:Event):void{
for(var i:int=0;i<maxlb; i++){
//PLACE DO LOOP INSIDE TO GENERATE EMPTY IN RANDOM COORDS
//add the blockades to the canvas
myblockadeSprite = new Sprite();
stage.addChild(myblockadeSprite);
//Get the actual picture from the library
blockade = new Blockade();
myblockadeSprite.addChild(blockade);
//Going to load up the array with the sprites
myBlockadeHolder[i] = myblockadeSprite;
myBlockadeHolder[i].y = Math.random()*390 + 10;
myBlockadeHolder[i].x = Math.random()*390 + 10;
myBlockadeHolder[i].rotation = Math.random()*360;
while(myBlockadeHolder[i].hitTestObject(Tank)){
myBlockadeHolder[i].y = Math.random()*390 + 10;
myBlockadeHolder[i].x = Math.random()*390 + 10;
}
}
for(var t:int=0;t<maxlb; t++){
for(var d:int=0;d<maxlb; d++){
while(myBlockadeHolder[t].hitTestObject(myBlockadeHolder[d])&& t!=d){
myBlockadeHolder[t].y = Math.random()*390 + 10;
myBlockadeHolder[t].x = Math.random()*390 + 10;
}
}
}
stage.removeEventListener(Event.ENTER_FRAME, dropblockade);
}//Blockade Code
//variables for target
var mytargetSprite:Sprite;
//target is the linkage name in the library
var target:Target;
//Create an array to hold multiple sprites
var mytargetHolder:Array = new Array();
//Create a counter to keep track of the number of sprites
var TargetCounter:int = 0;
//Maximum number of sprites on the canvas
var maxtrgs:int = 3;
//Keypress Code
stage.addEventListener(Event.ENTER_FRAME, droptarget);
function droptarget(evt:Event):void{
for(var i:int=0;i<maxtrgs; i++){
//PLACE DO LOOP INSIDE TO GENERATE EMPTY IN RANDOM COORDS
//add the targets to the canvas
mytargetSprite = new Sprite();
stage.addChild(mytargetSprite);
//Get the actual picture from the library
target = new Target();
mytargetSprite.addChild(target);
//Going to load up the array with the sprites
mytargetHolder[i] = mytargetSprite;
mytargetHolder[i].y = Math.random()*390 + 10;
mytargetHolder[i].x = Math.random()*390 + 10;
while(mytargetHolder[i].hitTestObject(Tank)){
mytargetHolder[i].y = Math.random()*390 + 10;
mytargetHolder[i].x = Math.random()*390 + 10;
}
}
for(var t:int=0;t<maxtrgs; t++){
for(var d:int=0;d<maxtrgs; d++){
while(mytargetHolder[t].hitTestObject(mytargetHolder[d])&& t!=d){
mytargetHolder[t].y = Math.random()*390 + 10;
mytargetHolder[t].x = Math.random()*390 + 10;
}
}
for(var w:int=0;w<maxtrgs; w++){
while(mytargetHolder[t].hitTestObject(myBlockadeHolder[w])&& t!=w){
mytargetHolder[t].y = Math.random()*390 + 10;
mytargetHolder[t].x = Math.random()*390 + 10;
}
}
}
stage.removeEventListener(Event.ENTER_FRAME, droptarget);
}//Target Code
function getRadians(delta_x:Number, delta_y:Number):Number{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0){
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #param radians Takes radians
* #return Returns degrees
*/
function getDegrees(radians:Number):Number{
return Math.floor(radians/(Math.PI/180));
}
function TextCounter(e:Event):void{
PointCounter.text = String(Points);
LifeCounter.text = String(Life);
}
I'm not really a physics guy but I can refer you to an article/tutorial that will most likely help you solve this issue. If it does, please post your fixed code as an answer because that's a better/more direct answer for this question. If not, hopefully someone else will come along with a better answer:
http://blog.generalrelativity.org/actionscript-30/dynamic-circlecircle-collision-detection-in-actionscript-3/