Help needed throwing a ball in AS3
- by Opoe
I'm working on a flash game, coding on the time line.
What I'm trying to accomplish is the following:
With the mouse you swing and throw/release a ball which bounces against the walls and eventualy comes to point where it lays still (like a real ball).
I allmost had it working, but now the ball sticks to the mouse, in stead of being released, my question to you is: Can you help me make this work and explain to me what I did wrong?
You can simply preview my code by making a movieclip named 'circle' on a 550x400 stage.
stage.addEventListener(Event.ENTER_FRAME, circle_update);
var previousPostionX:Number;
var previousPostionY:Number;
var throwSpeedX:Number;
var throwSpeedY:Number;
var isItDown:Boolean;
var xSpeed:Number = 0;
var ySpeed:Number = 0;
var friction:Number = 0.96;
var offsetX:Number = 0;
var offsetY:Number = 0;
var newY:Number = 0;
var oldY:Number = 0;
var newX:Number = 0;
var oldX:Number = 0;
var dragging:Boolean;
circle.buttonMode = true;
circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
circle.addEventListener(Event.ENTER_FRAME, throwcircle);
circle.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
circle.addEventListener(MouseEvent.MOUSE_UP, released);
function mouseDownHandler(e:MouseEvent):void
{
dragging = true;
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
offsetX = mouseX - circle.x;
offsetY = mouseY - circle.y;
}
function mouseUpHandler(e:MouseEvent):void
{
dragging = false;
}
function throwcircle(e:Event)
{
circle.x += xSpeed;
circle.y += ySpeed;
xSpeed *= friction;
ySpeed *= friction;
}
function changeFriction(e:Event):void
{
friction = e.target.value;
trace(e.target.value);
}
function circle_update(e:Event){
if ( dragging == true ) { circle.x = mouseX - offsetX;
circle.y = mouseY - offsetY; }
if(circle.x + (circle.width * 0.50) >= 550){ circle.x = 550 - circle.width * 0.50; }
if(circle.x - (circle.width * 0.50) <= 0){ circle.x = circle.width * 0.50; }
if(circle.y + (circle.width * 0.50) >= 400){ circle.y = 400 - circle.height * 0.50; }
if(circle.y - (circle.width * 0.50) <= 0){ circle.y = circle.height * 0.50; }
}
function clicked(theEvent:Event) {
isItDown =true;
addEventListener(Event.ENTER_FRAME, updateView);
}
function released(theEvent:Event) {
isItDown =false;
}
function updateView(theEvent:Event) {
if (isItDown==true){
throwSpeedX = mouseX - previousPostionX;
throwSpeedY = mouseY - previousPostionY;
circle.x = mouseX;
circle.y = mouseY;
}
else{
circle.x += throwSpeedX;
circle.y += throwSpeedY;
throwSpeedX *=0.9;
throwSpeedY *=0.9;
}
previousPostionX= circle.x;
previousPostionY= circle.y;
}