Lined drawn at stage appear on the next and previous frames - actionscript-3

I am using code for matching objects by drawing lines, the code working well but the lines drawn appear on next and previous frames when pressing next and previous buttons
`
import flash.events.MouseEvent;
import flash.display.Shape;
import flash.geom.Point;
var p1:Point = new Point();
var p2:Point = new Point();
stage.addEventListener(MouseEvent.MOUSE_DOWN, setP1);
function setP1(e:MouseEvent):void {
p1.x=mouseX;
p1.y=mouseY;
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
s=new Shape();
stage.addChild(s);
}
var s:Shape;
function draw(e:MouseEvent):void {
s.graphics.clear();
s.graphics.lineStyle(4,0xff0000, 1);
s.graphics.moveTo(p1.x, p1.y);
p2.setTo(mouseX, mouseY);
s.graphics.lineTo(p2.x, p2.y)
}
stage.addEventListener(MouseEvent.MOUSE_UP, end);
function end(e:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, draw);
if (MC_1.hitTestPoint(p1.x,p1.y) && MC_1_1.hitTestPoint(p2.x, p2.y))
{
}
else {
s.graphics.clear();
}
}
`

Ok, I put a bit of thought into it and found out that you
attach the Shapes directly to the stage rather then to the current context
don't bother to keep track of them
I enhanced your script a bit so that it keeps everything you create there (I don't know if you are working with multiple lines, so just in case), and there's a cleanUp() method you should call to undo literally everything the rest of the script does.
import flash.events.MouseEvent;
import flash.display.Shape;
import flash.geom.Point;
var P1:Point = new Point;
var P2:Point = new Point;
// A list of Shapes that will probably stockpile here.
var Slist:Array = new Array;
// The Shape to work with.
var S:Shape;
// Subscribe to the event to start drawing.
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function onDown(e:MouseEvent):void
{
// Subscribe to the relevant events.
stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
// Create an object for drawing.
S = new Shape;
Slist.push(S);
stage.addChild(s);
P1.x = S.mouseX;
P1.y = S.mouseY;
// First draw.
onDraw(e);
}
// Draw the line every time the mouse moves.
function onDraw(e:MouseEvent):void
{
// Memorize the endpoint coordinates.
P2.x = S.mouseX;
P2.y = S.mouseY;
// Drawing routine.
S.graphics.clear();
S.graphics.lineStyle(4,0xff0000, 1);
S.graphics.moveTo(P1.x, P1.y);
S.graphics.lineTo(P2.x, P2.y);
}
// End the drawing process.
function onUp(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onUp);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
// Last draw,
onDraw(e);
// Convert Points to stage coordinates. I know they are identical in
// the present setup, but it is not the reason to ignore the operation.
var GP1:Point = S.localToGlobal(P1);
var GP2:Point = S.localToGlobal(P2);
var aHit1:Boolean = MC_1.hitTestPoint(GP1.x, GP1.y);
var aHit2:Boolean = MC_1_1.hitTestPoint(GP2.x, GP2.y);
if (aHit1 && aHit2)
{
// Whatever you need to do here.
}
else
{
// Erase the unneeded Shape.
stage.removeChild(S);
var anIndex:int = Slist.indexOf(S);
if (anIndex > -1) Slist.splice(anIndex, 1);
S.graphics.clear();
S = null;
}
}
// Call this at the same time you go to another frame.
function cleanUp():void
{
// Clean the stockpiled objects if any.
while (Slist.length)
{
S = Slist.pop();
if (!S) continue;
if (!(S is Shape)) continue;
S.graphics.clear();
if (!S.parent) continue;
S.parent.removeChild(S);
}
// Destroy all the relevant objects.
S = null;
P1 = null;
P2 = null;
Slist = null;
// Finally, unsubscribe from DOWN handler (and the rest just in case).
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onUp);
stage.removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
}

Related

AS3 vertical shooter: Mouse click not working

I'm just trying to make a simple vertical shooter, one where the player's ship is controlled by the mouse and fires a laser when you click the mouse. However, when I try running the code, I keep getting the same error message:
"1046: Type was not found or was not a compile-time constant: MouseEvent."
The thing is, I declared the MouseEvent. I know I did. It is as follows:
--==--
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class SpaceShooter_II extends MovieClip //The public class extends the class to a movie clip.
{
public var army:Array; //the Enemies will be part of this array.
///*
//Laser Shots and Mouse clicks:
import flash.events.MouseEvent;
public var playerShot:Array; //the player's laser shots will fill this array.
public var mouseClick:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);
//*/
//Back to the rest of the code:
public var playerShip:PlayerShip; //This establishes a variable connected to the PlayerShip AS.
public var onScreen:GameScreen; //This establishes a variable that's connected to the GameScreen AS.
public var gameTimer:Timer; //This establishes a new variable known as gameTimer, connected to the timer utility.
///*
//Functions connected to Shooting via mouse-clicks:
public function mouseGoDown(event:MouseEvent):void
{
mouseClick = true;
}
public function mouseGoUp(event:MouseEvent):void
{
mouseClick = false;
}
//*/
//This function contains the bulk of the game's components.
public function SpaceShooter_II()
{
//This initiates the GameScreen.
onScreen = new GameScreen;
addChild ( onScreen );
//This sets up the enemy army.
army = new Array(); //sets the "army" as a NEW instance of array.
var newEnemy = new Enemy( 100, -15); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
army.push ( newEnemy ); //the new enemy is added to the army.
addChild( newEnemy ); //the new enemy is added to the game.
//This sets up the player's avatar, a spaceship.
playerShip = new PlayerShip(); //This invokes a new instance of the PlayerShip...
addChild( playerShip ); //...And this adds it to the game.
playerShip.x = mouseX; //These two variables place the "playerShip" on-screen...
playerShip.y = mouseY; //...at the position of the mouse.
///*
//This sets up the player's laser shots:
playerShot = new Array(); //sets the "army" as a NEW instance of array.
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
playerShot.push ( goodShot ); //the new enemy is added to the army.
addChild( goodShot ); //the new enemy is added to the game.
//*/
//This sets up the gameTimer, where a lot of the action takes place.
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
//This function contains the things that happen during the game (player movement, enemy swarms, etc.)
public function onTick( timerEvent:TimerEvent ):void
{
//This "if" statement is where the array that contains the enemy ships is initialized.
if ( Math.random() < 0.05 ) //This sets the number of ships showing up at once.
{
var randomX:Number = Math.random() * 800 //Generates a random number between 0 and 1.
var newEnemy:Enemy = new Enemy ( randomX, -15 ); //This shows where the enemy starts out--at a random position on the X plane, but at a certain points on the Y plane.
army.push( newEnemy ); //This adds the new enemy to the "army" Array.
addChild( newEnemy ); //This makes the new enemy part of the game.
}
//This "for" statement sends the enemies downward on the screen.
for each (var enemy:Enemy in army) //Every time an enemy is added to the "army" array, it's sent downward.
{
enemy.moveDown(); //This is the part that sends the enemy downward.
//And now for the collision part--the part that establishes what happens if the enemy hits the player's spaceship:
if ( playerShip.hitTestObject ( enemy ) ) //If the playerShip makes contact with the enemy...
{
gameTimer.stop(); //This stops the game.
dispatchEvent( new PlayerEvent(PlayerEvent.BOOM) ); //This triggers the game over screen in the PlayerEvent AS
}
}
//This, incidentally, is the player's movement controls:
playerShip.x = mouseX;
playerShip.y = mouseY;
///*
//And this SHOULD be the shooting controls, if the mouse function would WORK...
if ( mouseClick = true )
{
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new lasers. There's new variable in the statement, hence we call THIS a variable.
playerShot.push ( goodShot ); //the new laser is added to the army.
addChild( goodShot ); //the new laser is added to the game.
}
for each (var goodlaser: goodLaser in goodShot)
{
goodlaser.beamGood();
}
//*/
}
}
}
--==--
Sorry if the brackets are coming in uneven, I just wanted to outline the code in its entirety, and show the parts I added where things started going wrong, so someone can tell me what I need to do to make this work.
Basically, everything else works...but when I work on the things connected to the mouse clicking and the array with the lasers, the program stops working. The error seems to be connected to the functions "mouseGoUp" and "mouseGoDown," but I'm not sure how to fix that.
This assignment is due March 8. Can someone help me, please?
Add this import flash.events.MouseEvent; to the top of your class and it should work. You need to import everything you use. That's why you get that error.
As well as importing MouseEvent, in the initialisation of your game, you should add event listeners to the stage which listen for the MOUSE_DOWN and MOUSE_UP events:
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
What would be simpler, though, would be to do away with the 'mouseClick' variable and have just a single MouseEvent listener which listens for the MOUSE_DOWN event and trigger your missle launch from the handler.
I had a game like this if you want the entire source i can give it to you but the main parts are
var delayCounter:int = 0;
var mousePressed:Boolean = false;
var delayMax:int = 5;//How rapid the fire is
var playerSpeed:int = 5;
var bulletList:Array = [];
var bullet:Bullet;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler,false,0,true);
stage.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler,false,0,true);
stage.addEventListener(Event.ENTER_FRAME,loop,false,0,true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function loop(e:Event):void
{
player.rotation = Math.atan2(mouseY - player.y,mouseX - player.x) * 180 / Math.PI + 90;
if (bulletList.length > 0)
{
for each (bullet in bulletList)
{
bullet.bulletLoop();
}
}
if (mousePressed)
{
delayCounter++;
if ((delayCounter == delayMax))
{
shootBullet();
delayCounter = 0;
}
}
if (upPressed)
{
player.y -= playerSpeed;
}
if (downPressed)
{
player.y += playerSpeed;
}
if (leftPressed)
{
player.x -= playerSpeed;
}
if (rightPressed)
{
player.x += playerSpeed;
}
}
function mouseDownHandler(e:MouseEvent):void
{
mousePressed = true;
}
function mouseUpHandler(e:MouseEvent):void
{
mousePressed = false;
}
function shootBullet():void
{
var bullet:Bullet = new Bullet(stage,player.x,player.y,player.rotation - 90);
bulletList.push(bullet);
stage.addChildAt(bullet,1);
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = true;
}
if (event.keyCode == 83)
{
downPressed = true;
}
if (event.keyCode == 65)
{
leftPressed = true;
}
if (event.keyCode == 68)
{
rightPressed = true;
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = false;
}
if (event.keyCode == 83)
{
downPressed = false;
}
if (event.keyCode == 65)
{
leftPressed = false;
}
if (event.keyCode == 68)
{
rightPressed = false;
}
}
BULLET CLASS
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage;
private var speed:Number = 10;//speed that the bullet will travel at
private var xVel:Number = 5;
private var yVel:Number = 5;
private var rotationInRadians = 0;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180;
}
public function bulletLoop():void
{
xVel = Math.cos(rotationInRadians) * speed;
yVel = Math.sin(rotationInRadians) * speed;
x += xVel;
y += yVel;
if (x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
deleteBullet();
}
}
public function deleteBullet()
{
this.visible=false
this.x=9999
this.y=9999
}
}
}

Action script 3 drawing app undo and redo function

Can anyone show me how can I make undo and redo function? so this is my current action script. I cant figure how to do it and i see some example in some web site, the action script is to long to under stand. Pls show a simple way that i can make this work..
sorry for bad grammar...
import flash.display.MovieClip;
import flash.events.MouseEvent;
var pen_mc:MovieClip;
var drawing:Boolean = false;
var penSize:uint = 1;
var penColor:Number = 0x000000;
var shapes:Vector.<Shape>=new Vector.<Shape>();
var position:int=0;
const MAX_UNDO:int=10;
function init():void{
pen_mc = new MovieClip();
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, isDrawing);
stage.addEventListener(MouseEvent.MOUSE_UP, finishedDrawing);
addChild(pen_mc);
}
init();
function startDrawing(e:MouseEvent):void{
trace("Pen Has started drawing");
drawing = true;
pen_mc.graphics.lineStyle(penSize, penColor);
pen_mc.graphics.moveTo(mouseX, mouseY);
}
function isDrawing(e:MouseEvent):void{
if(drawing){
pen_mc.graphics.lineTo(mouseX, mouseY);
}
}
function finishedDrawing(e:MouseEvent):void{
trace("finished drawing");
drawing = false;
var sh:Shape=new Shape();
sh.graphics.copyFrom(pen_mc.graphics); // put current state into the vector
shapes.push(sh);
if (shapes.length>MAX_UNDO) shapes.unshift(); // drop oldest state
position=shapes.indexOf(sh);
}
function undo():void {
if (position>0) {
position--;
pen_mc.graphics.copyFrom(shapes[position].graphics);
} // else can't undo
}
function redo():void {
if (position+1<shapes.length) {
position++;
pen_mc.graphics.copyFrom(shapes[position].graphics);
} // else can't redo
}
function btn_undo(e:MouseEvent):void
{
undo();
}
function btn_redo(e:MouseEvent):void
{
redo();
}
undo_btn.addEventListener(MouseEvent.CLICK, btn_undo);
redo_btn.addEventListener(MouseEvent.CLICK, btn_redo);
You can use copyFrom() in Shape.graphics to store current condition, and the same to "redo", as your canvas is a Shape.
var shapes:Vector.<Shape>=new Vector.<Shape>();
var position:int=0;
const MAX_UNDO:int=10;
...
function finishedDrawing(e:MouseEvent):void{
trace("finished drawing");
drawing = false;
var sh:Shape=new Shape();
sh.graphics.copyFrom(penMC.graphics); // put current state into the vector
shapes.push(sh);
if (shapes.length>MAX_UNDO) shapes.unshift(); // drop oldest state
position=shapes.indexOf(sh);
}
function undo():void {
if (position>0) {
position--;
penMC.graphics.copyFrom(shapes[position].graphics);
} // else can't undo
}
function redo():void {
if (position+1<shapes.length) {
position++;
penMC.graphics.copyFrom(shapes[position].graphics);
} // else can't redo
}
This approach lacks some features, as to drop part of undo/redo stack if first undone to a certain point, then drawn. You can try adding this function yourself.

Error: #1009: Type Error (Line #114)

I'm sort of a noob to flash, but I am programming a game right now, and I am trying to make my character move but i am getting error #1009 Here is my code in my "GameState".
Basically it errors out on any Keypress, I have my character named player (Player in the library) and it has another movie clip within it named WalkDown (I gave it an instance name of walkDown on the timeline) I am not really sure whats going on. Specifically it errors out on the line where its calling the frame name. Any help would be appreciated!
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class GameState extends MovieClip {
private var player:MovieClip;
private var walking:Boolean = false;
// is the character shooting
//private var shooting:Boolean = false;
// wlaking speed
private var walkingSpeed:Number = 5;
private var xVal:Number = 0;
private var yVal:Number = 0;
public function GameState() {
// constructor code
player = new Player();
addChild(player);
player.x = 300;
player.y = 300;
player.gotoAndStop("stance");
this.addEventListener(Event.ADDED_TO_STAGE, initialise);
}
private function initialise(e:Event){
// add a mouse down listener to the stage
//addEventListener(MouseEvent.MOUSE_DOWN, startFire);
// add a mouse up listener to the stage
//addEventListener(MouseEvent.MOUSE_UP, stopFire);
player.addEventListener(Event.ENTER_FRAME,motion);
stage.addEventListener(KeyboardEvent.KEY_UP,onKey);
// add a keyboard down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, offKey);
stage.focus = stage;
// Add keyboard events
}
private function motion(e:Event):void{
// if we are currently holding the mouse down
//if (shooting){
//FIRE
//fire();
//}
player.x += xVal;
player.y += yVal;
}
//private function startFire(m:MouseEvent){
//shooting = true;
//}
//private function stopFire(m:MouseEvent){
//shooting = false;
//}
private function onKey(evt:KeyboardEvent):void
{
trace("key code: "+evt.keyCode);
switch (evt.keyCode)
{
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.S :
yVal = - walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.A :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.D :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
}
}
private function offKey(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.W :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.S :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.A :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.D :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
}
}
// Players Motion
private function fire():void{
var b= new Bullet();
// set the position and rotation of the bullet
b.rotation = rotation;
b.x = x;
b.y = y;
// add bullets to list of bullets
MovieClip(player).bullets.push(b);
// add bullet to parent object
player.addChild(b);
// play firing animation
player.shooting.gotoAndPlay("fire");
}
}
}
You were saying the Error #1009 ( Cannot access a property or method of a null object reference ) arises when you do
player.walkDown.gotoAndPlay("walking");
If so, that is because you have to first go to the frame where the WalkDown MovieClip is in before you can access it.
If say your "stance" frame is in frame 1 and your WalkDown MovieClip is in frame 2. Your code in the onKey function should look like:
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.gotoAndStop(2); // player.walkDown is now accessible //
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;

Some errors in flash AS3 game, almost completed with lot of effort and help received

First I really want to thank you for all the help you have given me so far, since I did not know anything about AS3 (basics gotoAnd stuff only) I came to Stackoverflow searching for some code already made but I was encouraged by some members to make the code by myself, now after almost 2 weeks and thanks to a lot of great people my soccer penalty kick game is almost finished, I really love this place.
I know I have to work on some collisions and other stuff since currently the game is not the best (remember I’m just a newbie), but Unfortunately while checking the game functioning by playing it over and over again, I have found the following:
1- When you get 3 fails, then game is over and a play again button appears after some animation, you click on it and everything seems to be fine, but when you continue playing the second time you reach 3 fails, when you click the button a new cursor appears??? Please help
2- I tried millions of times to make the ball move with speed and to animate its trajectory but was unable to make it, any help on this will be highly appreciated. I have speed variables and gravity but I didn’t know how to use them
3- I'm getting a actionscript error related to a removeChild, I tried many times removing some lines but I´m unable to fix it.
4- I'm using too many timers, I don't know if this is recommendable.
Here is the .fla file https://rapidshare.com/files/1702748636/kicks.fla just in case anybody want to try the game (this is really simple since it is my 1st AS project) and want to help me with the code and help me improving the game, and here is the code if somebody does not need to get into the file (I know this place is full of really smart people), once I finish it I know I will be able to do a lot of stuff with AS3.
var score:Number;
var angle:Number;
var speed:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
function initializeGame( ):void
{
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
cursor = new Cursor();
addChild(cursor);
cursor.enabled = true;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function dragCursor(event:MouseEvent):void
{
cursor.x = this.mouseX;
cursor.y = this.mouseY;
}
initializeGame();
var mouse = this.Mouse;
function kick(evt:Event)
{
removeChild(cursor);
pateador_mc.play();
var timer:Timer = new Timer(500,1);
timer.addEventListener(TimerEvent.TIMER, delayedAction);
timer.start();
function delayedAction(e:TimerEvent)
{
moveBall();
}
}
speed=-100000;
var ease:int = 100;
var gravity:Number = 0.5;
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
ball.x = mouseX + Math.cos(angle);
ball.y = mouseY + Math.sin(angle) ;
ballRotation = true;
stage.removeEventListener(MouseEvent.CLICK, kick);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
var timer3:Timer = new Timer(3000,1);
timer3.addEventListener(TimerEvent.TIMER, delayedAction3);
timer3.start();
function delayedAction3(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
addChild(cursor);
keeper.gotoAndStop(1);
}
}
else
{
fails_mc.play();
failed++;
var timer2:Timer = new Timer(3000,1);
timer2.addEventListener(TimerEvent.TIMER, delayedAction2);
timer2.start();
function delayedAction2(e:TimerEvent)
{
ball.x = 296.35;
ball.y = 353.35;
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
addChild(cursor);
keeper.gotoAndStop(1);
}
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
}
}
function showScore():void{
goles_txt.text ="" +score;
}
trace (score);
function gameFinished(){
gameOver.play ();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
timer2.stop();
Mouse.show();
this.mouseX=cursor.x ;
this.mouseY=cursor.y;
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain():void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
var timer4:Timer = new Timer(1000,1);
timer4.addEventListener(TimerEvent.TIMER, delayedAction3);
timer4.start();
function delayedAction3(e:TimerEvent)
{
initializeGame();
}
}
}
I’ll really appreciate it guys , I promise I won’t be bothering again for a long time
1/3.
Problem 1 & 3 are the same problem. Looks like your trying to remove the cursor from the stage (removeChild) every click (so it will error after the first click because it's no longer a child of anything). Your adding it back on your delayedAction2 which doesn't run unless your hit test is true and only after 3 seconds. On initialize game you create a whole new cursor and add that to the stage which is why you get a duplicate after the first game.
Rather than removeChild the cursor, it might better to just set it's visibility to false/true and only create it once.
You'll need to use an EnterFrame handler, or timer, or tween for this. I can post an example later.
I can't figure out why you're using timers at all or need to delay your functions, except maybe to allow time for the kick animation?
You're code is very disorganized, naming functions things like 'delayedAction' is bad as it doesn't really tell you anything about the purposed of the function. You also have way too much functions inside of other functions. Here is a quick refactoring of your code I've done to hopefully teach a few things. I've also added the tween for the ball animation.
import flash.events.Event;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
var score:Number;
var cursor:MovieClip;
var failed:Number;
var ballRotation:Boolean = false;
var ballTweenX:Tween;
var ballTweenY:Tween;
var targetCursor = new Cursor(); //only want one of these and you want it to exist the whole time so keep out here.
addChild(targetCursor);
initializeGame();
function initializeGame( ):void
{
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
ball.x = 296.35;
ball.y = 353.35;
score=0;
failed=0;
targetCursor.visible = true;
Mouse.hide();
}
function dragCursor(event:MouseEvent):void
{
targetCursor.x = this.mouseX;
targetCursor.y = this.mouseY;
}
function kick(evt:Event)
{
//removeChild(targetCursor);
targetCursor.visible = false;
pateador_mc.play();
stage.removeEventListener(MouseEvent.CLICK, kick); //move this here, because you don't the option kick again while already kicking
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor); //added this, you probably don't want the target moving after the click...
setTimeout(moveBall, 500);//cleaner and more efficient than using a timer for a one time delayed call.
}
function moveBall()
{
var targetX:Number = mouseX;
var targetY:Number = mouseY;
var angle = Math.atan2(targetY,targetX);
targetX = mouseX + Math.cos(angle);
targetY = mouseY + Math.sin(angle) ;
ballRotation = true;
ballTweenX = new Tween(ball, "x", null, ball.x, targetX, .3, true);
ballTweenY = new Tween(ball, "y", null, ball.y, targetY, .3, true);
ballTweenY.addEventListener(TweenEvent.MOTION_FINISH, ballTweenDone,false,0,true);
if (ballRotation==true)
{
keeper.gotoAndStop(1 + Math.floor(Math.random() * keeper.totalFrames));
ball.play();
}
}
function stopBallTween():void {
ballTweenX.stop();
ballTweenY.stop();
}
function ballTweenDone(e:TweenEvent):void {
if (ball.hitTestObject ( keeper)){
ball.y=keeper.x-ball.height- ball.width;
trace ("Tomela");
}
if (ball.hitTestObject(goalie) && ball.y>69 /*&& ball.y<178 && ball.X>139 && ball.x<466*/)
{
gol_mc.play();
score ++;
showScore();
}else
{
fails_mc.play();
failed++;
trace(failed);
if (failed==3) {
gameFinished();
trace("YOU LOST");
return; //added this because you don't want the rest of this function running if it's a game over
}
}
setTimeout(resetShot, 3000); //you had the code I put in resetShot repeated twice
trace(score);
}
function resetShot():void {
ball.x = 296.35;
ball.y = 353.35;
targetCursor.visible = true;
keeper.gotoAndStop(1);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
stage.addEventListener(MouseEvent.CLICK, kick);
}
function showScore():void{
goles_txt.text ="" +score;
}
function gameFinished(){
gameOver.play();
stage.removeEventListener(MouseEvent.CLICK, kick);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragCursor);
Mouse.show();
//this.mouseX=cursor.x ;
//this.mouseY=cursor.y; //These are read only properties, your can't set the mouse position...
again_btn.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
}
function playAgain(e:Event = null):void{
gameOver.gotoAndPlay(31);
fails_mc.gotoAndStop(1);
keeper.play();
setTimeout(initializeGame, 1000);
}

AS3 - If symbol's coordinates arrive here?

I'm using Flash Professional CS5.5 and I need to make an app where there is a ball (symbol) that moves using the accelerometer and I want that, when the ball coordinates A reach this coordinates B it goes to frame 2 (gotoAndPlay(2)). I have to find the ball coord first, right? How do I make this?
Here is the code I've now
c_ball.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void{
c_ball.startDrag();}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void{
c_ball.stopDrag();}
would it work if, after retriving the coordinates?
function f_level (e) if (c_ball.x==100 && c_ball.y==100) {
gotoAndStop(2);}
MOUSE_UP and MOUSE_DOWN are not what you need if you're looking for Accelerometer data. You want the Accelerometer class and associated events.
Try something like this:
import flash.sensors.Accelerometer;
import flash.events.AccelerometerEvent;
var accel:Accelerometer = new Accelerometer();
accel.addEventListener(AccelerometerEvent.UPDATE, handleAccelUpdate);
Update handler:
function handleAccelUpdate(e:AccelerometerEvent):void{
//inside this function you now have access to acceleration x/y/z data
trace("x: " + e.accelerationX);
trace("y: " + e.accelerationY);
trace("z: " + e.accelerationZ);
//using this you can move your MC in the correct direction
c_ball.x -= (e.accelerationX * 10); //using 10 as a speed multiplier, play around with this number for different rates of speed
c_ball.y += (e.accelerationY * 10); //same idea here but note the += instead of -=
//you can now check the x/y of your c_ball mc
if(c_ball.x == 100 && c_ball.y == 100){
trace("you win!"); //fires when c_ball is at 100, 100
}
}
Now this will let you "roll" your MC off the screen so you're probably going to want to add some kind of bounds checking.
Check out this great writeup for more info:
http://www.republicofcode.com/tutorials/flash/as3accelerometer/
An easy and save way is to use colission detection, instead of testing for exectly one position ( what is hard to meet for users) you go for a target area :
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class Hittester extends Sprite
{
var ball:Sprite = new Sprite();
var testarea:Sprite = new Sprite();
public function Hittester()
{
super();
ball.graphics.beginFill(0xff0000);
ball.graphics.drawCircle(0,0,10);
testarea.graphics.beginFill(0x00ff00);
testarea.graphics.drawRect(0,0,50,50);
testarea.x = 100;
testarea.y = 100;
// if testarea should be invisble
/*testarea.alpha = 0;
testarea.mouseEnabled = false;
*/
ball.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
addChild(testarea);
addChild(ball);
}
private function startDragging( E:Event = null):void{
ball.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}
private function stopDragging( E:Event = null):void{
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
ball.stopDrag();
test();
}
private function test():void{
if( ! ball.hitTestObject(testarea) ){
ball.x = 10;
ball.y = 10;
}
else{
// here goes next frame command ;)
}
}
}
}