AS3 - Drag using If statement to Next Scene. - actionscript-3

I am making an interactive game - and I have this code so far. Where drop1 is a coin and the user drops it into target1 (box) and once they have done they they are able to watch the video play in the next scene. AS you can see when drop1 (coin) is dropped onto the box the coin then disappears
//Array to hold the target instances, the drop instances,
//and the start positions of the drop instances.
var hitArray:Array = new Array(hitTarget1);
var dropArray:Array = new Array(drop1);
var positionsArray:Array = new Array();
//This adds the mouse down and up listener to the drop instances
//and add the starting x and y positions of the drop instances
//into the array.
for (var i:int = 0; i < dropArray.length; i++) {
dropArray[i].buttonMode = true;
dropArray[i].addEventListener(MouseEvent.MOUSE_DOWN, mdown);
dropArray[i].addEventListener(MouseEvent.MOUSE_UP, mUp);
positionsArray.push({xPos:dropArray[i].x, yPos:dropArray[i].y});
}
//This drags the object that has been selected and moves it
//to the top of the display list. This means you can't drag
//this object underneath anything.
function mdown(e:MouseEvent):void {
e.currentTarget.startDrag();
setChildIndex(MovieClip(e.currentTarget), numChildren - 1);
}
//This stops the dragging of the selected object when the mouse is
//released. If the object is dropped on the corresponding target
//then it get set to the x and y position of the target. Otherwise
//it returns to the original position.
function mUp(e:MouseEvent):void {
var dropIndex:int = dropArray.indexOf(e.currentTarget);
var target:MovieClip = e.currentTarget as MovieClip;
target.stopDrag();
if (target.hitTestObject(hitArray[dropIndex])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
drop1.visible = false;
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
NOW... I want the code to know when the user has dropped the coin in the box and IF the user has they can then watch the video but can only watch the video if they drop the coin in box. How can i code this?
please help.
thank you

If you're still struggling you can always try reading the MANUAL..? I suspect this is why you've had no answer so far. Travelling between frames/scenes requires either gotoAndPlay or gotoAndStop. Check: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/MovieClip.html#gotoAndPlay()
Look at example two for scene jumping code. Where it says "intro" (frame label) it's okay to just use a number but scenes must have names.. e.g:
mc1.gotoAndPlay("intro", "Scene 12");
or in your case something like below (assuming you have named it as scene_video)
if (target.hitTestObject(hitArray[dropIndex])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
drop1.visible = false;
gotoAndStop(1, "scene_video"); }
Again I'm assuming your video player is on frame 1 of that scene so stopping there allows users a chance to watch the video player.

Related

actionscript 3.0 drag and swap

This is my code for dragging and dropping movie clips into their matching movie clip targets. I would like to make a jigsaw puzzle game where all the pieces are in some place, and when one piece is dragged onto another, they two pieces swap and if the piece matches the target it should lock into place and stay there with this code. Only problem is I don't know how to make the pieces swap locations. Any ideas?? Is this even possible?? Please help...
function pickupObject(event:MouseEvent):void {
event.target.startDrag(true);
event.target.parent.addChild(event.target);
objectoriginalX=event.target.x;
objectoriginalY=event.target.y;
}
function dropObject(event:MouseEvent):void {
event.target.stopDrag();
var matchingTargetName:String="target"+ event.target.name;
var matchingTarget:DisplayObject=getChildByName(matchingTargetName);
if(event.target.dropTarget != null && event.target.dropTarget.parent==matchingTarget) {
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
event.target.buttonMode=false;
event.target.x=matchingTarget.x;
event.target.y=matchingTarget.y;
}
}
Store drag and drop objects in two different arrays and x and y positions also. Consider 3 drag and drop objects.
var drag:Array = new Array(drag0, drag1, drag2);
var drop:Array = new Array(drag0_target, drag1_target, drag2_target);
var points:Array = new Array({x:drag_0.x, y:drag_0.y},...);
//this regular expression will return a digit number from given string.
var pattern:RegExp = /\d/;
note: drop array object names should be start with drag object names. For matching purpose.
Add mouse listeners to the drag array objects.
MouseDownHandler()
e.target.startDrag();
MouseUpHandler()
//create a tmp variable for store the current drag object number;
tmp = e.target.name.match(pattern);
for(i=0;i<drop.length; i++){
//Check whether the hit occurred in the drop clips
if(MovieClip(e.target).hitTestObject(this.drop[i])){
//Check whether the object has been dropped in a right place.
if(drop[i].name.split("_")[0] == e.target.name){
e.target.x = drop[i].x;
e.target.y = drop[i].y;
}else{
//else place the drag object into the initial position.
e.target.x = points[tmp].x;
e.target.y = points[tmp].y;
}
}
}
Good luck.

Delete the bitmap directly behind newly placed bitmap - AS3

Tile-based map maker. I want to click the canvas, it places a tile, change tile, click the canvas and it replace the bitmap that I clicked on. .alpha shows clearly that all I am doing is stacking tiles... which will become a problem when I make a 2d array from it. I imagine that there's a way to make layers that they could sit on, but I haven't been able to find anything about it. Here's the code -
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
}
}
I want to delete the tile below the new tile that I place. I place a tile... I place a diferent tile over the old tile, I want the old tile to delete... not just stack tiles.
Sounds like you just need to keep track of the previous tile, then remove it accordingly:
private var curTile:Bitmap; //let's keep a reference to the current tile
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
//if there is a current tile, remove it from the display list
if(curTile){
removeChild(curTile);
}
//create your new one as usual
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
curTile = newTile; //make the current tile the one just created
}
}
EDIT
Based off you comment, this seems more like the solution you're looking for.
Sounds like you just want the tile to go away when clicked.
private var curTile:Bitmap; //let's keep a reference to the current tile
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
//add a click listener to delete this tile when clicked
newTile.addEventListener(MouseEvent.CLICK, deleteTile, false, 0 true); //make sure the event listener has a weak listener
}
}
private function deleteTile(e:Event):void {
var tile:Bitmap = e.currentTarget as Bitmap;
if(tile.parent) tile.parent.removeChild(tile);
}
I pushed it all into an array, with placeholder strings for every unoccupied cell. Then I check if the index at my current mouse position is a DisplayObject and remove it if it is, replacing it with the new tile.
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
if(aarray[mouseYind][mouseXind] is DisplayObject)
{
removeChild(aarray[mouseYind][mouseXind]);
}
var newTile:Sprite = new Sprite();
var bmp:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.addChild(bmp);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
addChild(newTile);
aarray[mouseYind][mouseXind] = newTile;
}
}

Enemy move randomly

To make things quick, I have an arrangement of tiles that a player and an enemy are on.
public static var floor1:Array = new Array(7);
floor1[0] = [0,1,1,1,1,1,0];
floor1[1] = [1,1,1,1,1,1,1];
floor1[2] = [1,1,1,0,1,1,1];
floor1[3] = [1,1,0,0,0,1,1];
floor1[4] = [1,1,1,0,1,1,1];
floor1[5] = [1,1,1,1,1,1,1];
floor1[6] = [0,1,1,1,1,1,0];
public function Main()
{
var tilew:int = 60;
var tileh:int = 60;
for (var i:int=0; i<floor1.length; i++)
{
for (var u:int=0; u<floor1[i].length; u++)
{
var cell:MovieClip = new Tile();
cell.gotoAndStop(floor1[i][u]);
cell.x = ((u-i)*tileh);
cell.y = ((u+i)*tilew/2);
addChild(cell);
cell.addEventListener(MouseEvent.ROLL_OVER, mouseover);
cell.addEventListener(MouseEvent.ROLL_OUT, mouseout);
cell.addEventListener(MouseEvent.CLICK, mouseclick);
cell.addEventListener(Event.ENTER_FRAME, beginfloor1);
}
}
var player:Player = new Player();
addChild(player);
player.mouseEnabled = false;
player.x = 5 * (tileh);
player.y = 5 * (tilew/2);
var enemy:Enemy = new Enemy();
addChild(enemy);
enemy.mouseEnabled = false;
enemy.x = 9 * (tileh);
enemy.y = 9 * (tileh/2);
My goal is to have the enemy move randomly on tiles in his range. What I did was create a square graphic called enemyVisionArea that checks which tile is hitting the enemy, which is basically surrounding tiles.
I have a timer function that tells the enemy to move every 5 seconds if the player isn't near him and if he's next to an available tile.
function timerenemy (event:TimerEvent){
if (enemy.enemyVisionArea.hitTestObject(enemyMover) && !player.visionPoint.hitTestObject(enemyMover.tileMiddle))
{
enemy.x = (enemyMover.x)+55;
enemy.y = (enemyMover.y)+20;
trace("moved");
}
}
enemyMover is a variable that I made equal to the tile objects.
function beginfloor1(event:Event)
{
enemyMover = event.currentTarget as Tile;
}
It just stays where it is. I'm just want to have the enemy move on its own on any tile that its enemyVisionArea is hitTesting a nearby tile. The beginfloor1 function doesn't seem to be working. Is there any way I can declare enemyMover = event.currentTarget as Tile and have the enemy move on a random tile that its enemyVisionArea is hitTesting?
If this is confusing, I can post the full code.
You are assigning 49 enterframe listeners which are called in sequence, and they ALL change one single variable to the cell they are attached to. Of course, the last tile is what's always assigned.
I expect that you want an enemy to check if there's a tile available for it to move to. You are essentially checking for one tile which is enemyMover - how do you determine what's that tile? You have to check all available tiles that are around the enemy, make a list of them and select one out of that list that's not the current tile, then move the enemy there.
So, first you need a complete tileset to be addressable from somewhere. The best way will be to declare a class-wide var tileset:Array and fill it where you make new tiles. Drop the Event.ENTER_FRAME listener from the code there, as it's useless. Then, in your timerevent that's for the enemy you do check all of the tileset if they are within your enemy's vision area (you use hitTestObject, I'd use clear distance grid-wise or coordinate-wise - it's a whole lot faster), if so, you add them to the TEMPORARY array you create within that function. Of course, if your enemy is at the currently processed cell, you ignore it - you have to move your enemy, not make him stand in place. Then, select (somehow, it's up to you) what cell your enemy should move to, and execute a move. Yes, if you want your enemy to move randomly, select a cell at random by its index via Math.floor(Math.random()*selectedcells.length).

how to remove a child object by removeChild()?

I'm trying to make a custom animated/shooter, from this tutorial: http://flashadvanced.com/creating-small-shooting-game-as3/
By custom, I mean customized, ie, my own version of it.
In it's actionscript, there's a timer event listener with function: timerHandler()
This function adds and removes child "star" objects on the stage (which the user has to shoot at):
if(starAdded){
removeChild(star);
}
and :
addChild(star);
Code works great, but error occurs on scene 2.
The code works great, and I even added some code while learning via google and stackflow to this flash file. I added Scene 2 to it too, and had it called after 9 seconds of movie time. But when it goes to Scene 2, it still displays the star objects and I've been unable to remove these "star" object(s) from Scene 2.
Here's the code I added:
SCENE 1:
var my_timer = new Timer(5000,0); //in milliseconds
my_timer.addEventListener(TimerEvent.TIMER, catchTimer);
my_timer.start();
var myInt:int = getTimer() * 0.001;
var startTime:int = getTimer();
var currentTime:int = getTimer();
var timeRunning:int = (currentTime - startTime) * 0.001; // this is how many seconds the game has been running.
demo_txt.text = timeRunning.toString();
function catchTimer(e:TimerEvent)
{
gotoAndPlay(1, "Scene 2");
}
SCENE 2:
addEventListener(Event.ENTER_FRAME,myFunction);
function myFunction(event:Event) {
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
my_timer.stop(); // you might need to cast this into Timer object
my_timer.removeEventListener(TimerEvent.TIMER, catchTimer);
Mouse.show();
}
stop();
=====================================================
I'm quite new as3, and have just created an account on StackOverflow... even though I've known and read many codes on it since quite some time.
Here's the Edited New Complete Code:
//importing tween classes
import fl.transitions.easing.*;
import fl.transitions.Tween;
//hiding the cursor
Mouse.hide();
//creating a new Star instance
var star:Star = new Star();
var game:Game = new Game();
//creating the timer
var timer:Timer = new Timer(1000);
//we create variables for random X and Y positions
var randomX:Number;
var randomY:Number;
var t:int = 0;
//variable for the alpha tween effect
var tween:Tween;
//we check if a star instance is already added to the stage
var starAdded:Boolean = false;
//we count the points
var points:int = 0;
//adding event handler on mouse move
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
//adding event handler to the timer
timer.addEventListener(TimerEvent.TIMER, timerHandler);
//starting the timer
timer.start();
addChild(game);
function cursorMoveHandler(e:Event):void{
//sight position matches the mouse position
game.Sight.x = mouseX;
game.Sight.y = mouseY;
}
function timerHandler(e:TimerEvent):void{
//first we need to remove the star from the stage if already added
if(starAdded){
removeChild(star);
}
//positioning the star on a random position
randomX = Math.random()*500;
randomY = Math.random()*300;
star.x = randomX;
star.y = randomY;
//adding the star to the stage
addChild(star);
//changing our boolean value to true
starAdded = true;
//adding a mouse click handler to the star
star.addEventListener(MouseEvent.CLICK, clickHandler);
//animating the star's appearance
tween = new Tween(star, "alpha", Strong.easeOut, 0, 1, 3, true);
t++;
if(t>=5) {
gotoAndPlay(5);
}
}
function clickHandler(e:Event):void{
//when we click/shoot a star we increment the points
points ++;
//showing the result in the text field
points_txt.text = points.toString();
}
And on Frame 5 :
//timer.stop();
//timer.removeEventListener(TimerEvent.TIMER, timerHandler);
// uncomment lines above if "timer" is something you've made
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
timer.stop(); // you might need to cast this into Timer object
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
Mouse.show();
stop();
There's no Scene 2 now, in this new .fla file...
Here's a screenshot of the library property of my flash file...: http://i.imgur.com/d2cPyOx.jpg
You'd better drop scenes altogether, they are pretty much deprecated in AS3. Instead, use Game object that contains all the cursor, stars and other stuff that's inside the game, and instead of going with gotoAndPlay() do removeChild(game); addChild(scoreboard); where "scoreboard" is another container class that will display your score.
Regarding your code, you stop having a valid handle to stage that actually contains that star of yours, because your have changed the scene. So do all of this before calling gotoAndPlay() in your catchTimer function.
function catchTimer(e:TimerEvent)
{
//timer.stop();
//timer.removeEventListener(TimerEvent.TIMER, timerHandler);
// uncomment lines above if "timer" is something you've made
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
my_timer.stop(); // you might need to cast this into Timer object
my_timer.removeEventListener(TimerEvent.TIMER, catchTimer);
Mouse.show();
gotoAndPlay(1, "Scene 2");
}
And the code for Scene 2 will consist of a single stop() - until you'll add something there. Also, there should be no event listeners, especially enter-frame, without a code to remove that listener! You add an enter-frame listener on Scene 2 and never remove it, while you need that code to only run once.
Use getChildAt.
function catchTimer(e:TimerEvent)
{
var childCount:int = this.numChildren - 1;
var i:int;
var tempObj:DisplayObject;
for (i = 0; i < childCount; i++)
{
tempObj = this.getChildAt(i);
this.removeChild(tempObj);
}
gotoAndPlay(1, "Scene 2");
}
This will remove all the children you added on scene 1 before going to scene 2.

as3 marquee select drag multiple child objects

Can anyone tell me how to achieve marquee selection effect with AS3 to select multiple movieclips by drawing a dynamic rectangle around them and then drag and drop them anywhere?
Don't use startDrag() if you need multiple objects to be draggable, since it only allows one object to be dragged at a time. Instead, listen for mouse events and do the moving manually:
var oldX:int;
var oldY:int;
var dragging:Boolean = false;
function onMouseDown(evt:MouseEvent):void {
dragging = true;
oldX = evt.stageX;
oldY = evt.stageY;
}
function onMouseMove(evt:MouseEvent):void {
if (!dragging) return;
var dX:int = evt.stageX - oldX;
var dY:int = evt.stageY - oldY;
for (int i = 0; i < selectedClips.length; i++) {
var clip:DisplayObject = selectedClips[i];
clip.x += dX;
clip.y += dY;
}
oldX = evt.stageX;
oldY = evt.stageY;
}
function onMouseUp(evt:MouseEvent):void {
dragging = false;
}
This code assumes that:
Your array of selected objects is called selectedClips.
Your array of selected objects all inherit from DisplayObject.
You have added event listeners on all draggable objects for the MOUSE_DOWN, MOUSE_MOVE, and MOUSE_UP mouse events which call these functions.
If any of those three conditions are not met, update my code or your code to work properly. Also, if you need to do any additional handling when the objects are dropped, you can use the mouse up handler to add custom code.