ActionScript 3.0 Changing Direction - actionscript-3

Alright let me make this clear. I am just doing out of interest. This is not a homework. I am doing it because I am interest in writing the ActionScript. I saw a guy website doing something amazing so I tried to copy and I want to do this:
Oh by the way you need to make a symbol and need to export for ActionScript and class name is "ball". And the button instant name is:bButton. So here's the script I wrote so far.
var boundaryRight:Number = stage.stageWidth;
var boundaryLeft:Number = 0;
var balls:Array;
var reverseRight:Number = 0;
var reverseLeft:Number = stage.stageWidth;
init();
function init(){
balls = new Array();
for(var i:Number = 0; i<10; i++){
var myBall:ball = new ball();
myBall.x=(Math.random()*boundaryRight);
myBall.y=50+i*40;
addChild(myBall);
balls.push(myBall);
}
}
addEventListener(Event.ENTER_FRAME,moveBall);
function moveBall(e:Event){
for(var i:Number = 0;i<10;i++){
var myBall:ball = balls[i];
myBall.x-=20;
if(myBall.x<boundaryLeft){
myBall.x=boundaryRight;
}
}
}
As you can see that code made the multiple ball go to left and looping over and over again. So here's what I want to do. I want to make a button and when I click the button it'll change direction like click and it change direction to right. I click it again and it'll go left again. How do I write the code for that?

Use two global variables direction and speed.
var direction:Number = 1;
var speed:Number = 20;
Instead of giving myBall.x-=20;
Give myBall.x += ( direction * speed );
In the click handling function of the button
Give direction *= -1;
You can also change speed like this.

Related

Arranging items in an inventory

I'm working on an inventory system I made following a short tutorial that leaves you stranded. I've managed to get the items removed and rearrange to the correct order somewhat. For some reason though, if I click on the last item in my inventory, then on the first item, the items do not rearrange correctly.
public class Inventory {
var itemsInInventory:Array;
var inventorySprite:Sprite;
var itemNum:int;
public function Inventory(parentMC:MovieClip) {
itemNum=0;
itemsInInventory = new Array();
inventorySprite = new Sprite();
inventorySprite.x = 50;
inventorySprite.y = 360;
parentMC.addChild(inventorySprite);
}
public function makeInventoryItems(arrayOfItems:Array){
for(var i:int = 0; i < arrayOfItems.length; i++){
arrayOfItems[i].addEventListener(MouseEvent.CLICK, getItem);
arrayOfItems[i].buttonMode = true;
}
}
public function getItem(e:MouseEvent){
var item:MovieClip = MovieClip(e.currentTarget);
itemsInInventory.push(item);
inventorySprite.addChild(item);
item.x = (itemsInInventory.length-1)*40;
item.y = 0;
item.removeEventListener(MouseEvent.CLICK, getItem);
item.addEventListener(MouseEvent.CLICK, useItem);
}
public function useItem(e:MouseEvent){
var item:MovieClip = MovieClip(e.currentTarget);
itemNum = item.x;
inventorySprite.removeChild(item);
itemsInInventory.splice(item, 1);
sortInventory();
}
public function sortInventory(){
for(var i:int = 0; i < itemsInInventory.length; i++){
if(itemsInInventory[i].x > itemNum){
itemsInInventory[i].x -= 40;
}
}
itemNum=0;
}
}
I belive thats all the coding info I need to provide for help solving this mystery.
Also, a link to the game for testing. If you would like a link for a download of the game, please ask.
LINK
Instead of substracting 40px, just set their position again:
for(var i:int = 0; i < itemsInInventory.length; i++){
itemsInInventory[i].x = i*40;
}
Also, I did not even know that it is possible to give an object reference to the splice function, I would rather use:
itemsInInventory.splice(itemsInInventory.indexOf(item), 1);
And remove the event listener from the item when you delete it from the inventory in the useItem function.
item.removeEventListener(MouseEvent.CLICK, useItem);
EDIT:
With Flash Player 10, Adobe introduced the Vector class which is kind of the same as the Array class, but it can only store one data type. In your case it would be MovieClip or Sprite. The Vector class is singificantly faster and more developer friendly because you can see the help from the IDE when you are typing myVector[i].. I recommend using that instead, although there is nothing wrong with Array. It is just outdated a bit, but is helpful when you want to store more data types.
myVector:Vector.<MovieClip> = new Vector.<MovieClip>();

AS3 reference movieclip by .name property

Yay, another simple noobie as3 question.
How can I reference a movieclip by its ".name" ?
I tried searching for a solution, but I couldn't find anything. Basically I have a set of movieclips added to the stage using a loop, so the way I found to diferentiate them was by giving them a .name of "something" + the Loop's "i". So now they are named something like "something1", "something2", "something3", and so on.
Now, I need to send some to a specific frame. Usually I would do something like:
something1.gotoAndStop(2);
But "something1" isnt the instance name, just the ".name". I cant find a way to reference it.
you want to use getChildByName("name") more info
import flash.display.MovieClip;
// create boxes
for(var i:int = 0 ; i < 4; i++){
var box:MovieClip = new myBox(); // myBox is a symbol in the library (export for actionscript is checked and class name is myBox
box.name = "box_" + i;
box.x = i * 100;
this.addChild(box);
}
// call one of the boxes
var targetBox:MovieClip = this.getChildByName("box_2") as MovieClip;
targetBox.gotoAndStop(2);
Accessing things by name is very prone to errors. It's not a good habit to get into if you're a newbie. I think a safer way to do this would be to store references to the things you're creating in the loop, for example in an array, and reference them by their indexes.
Example:
var boxes:Array = [];
const NUM_BOXES:int = 4;
const SPACING:int = 100;
// create boxes
for(var i:int = 0 ; i < NUM_BOXES:; i++){
var box:MovieClip = new MovieClip();
// You can still do this, but only as a label, don't rely on it for finding the box later!
box.name = "box_" + i;
box.x = i * SPACING;
addChild(box);
// store the box for lookup later.
boxes.push(box); // or boxes[i] = box;
}
// talk to the third box
const RESET_FRAME:int = 2;
var targetBox:MovieClip = boxes[2] as MovieClip;
targetBox.gotoAndStop(RESET_FRAME);
Note, I've also replaced many of the loose numbers with constants and vars which will also help your compiler notice errors.
You can use the parent to get the child by name. If the parent is the stage:
var something1:MovieClip = stage.getChildByName("something1");
something1.gotoAndStop(2);

randomize buttons on in as3 from array

I'm pretty novice to flash 5.5, im trying to build a quiz for my elementary students.
So far I have made the layout, created the image buttons, and I used to as3 to advance the quiz.
So what I'm, looking for is the ability to shuffle the image buttons/answers. Here is a sample of what i have so far.
the red ______
apple (button of apple) boy (button of boy) pineapple (button with pineapple)
In my example, the pictures are buttons, the correct answer is apple. I have tried to create an array, after hours of google searches. This is my code, I'm doing something wrong but I have no idea what. Please help.
Please help.
function Main() {
var button:Array = [];
button.push("choice1");
button.push("choice2");
button.push("choice3");
ShuffleArray(button);
trace(button);
}
function ShuffleArray(button:Array)
{
for (var i:int = button.length-1; i >=0; i--)
{
var randomIndex:int = Math.floor(Math.random()*(i+1));
var itemAtIndex:Object = button[randomIndex];
button[randomIndex] = button[i];
button[i] = itemAtIndex;
thanks in advance.
thanks in advance.
Try something more like this:
protected var button:Array=[choice1, choice2, choice3];//note no quotes, puts in the actual objects
function Main() {
super();
randomArray=shuffleArray(button);
var prevX:int = 0;
var space:int = 10;
//places the buttons from left to right in the order
//they were in the random array
//uses existing y
for (var i:int=0; i<randomArray.length; i++) {
var btn:DisplayObject = randomArray[i] as DisplayObject;
btn.x = prevX;
prevX = btn.x + btn.width + space;
}
}
protected function shuffleArray(inArray:Array):Array {
//create copy of array so as not to alter it
var tempArray = new Array().concat(inArray);
//resultarray (we'll be destroying the temp array)
var resultArray:Array = [];
while(tempArray.length>0) {
var index:int = int(Math.random() * tempArray.length);
//delete object from random location and put it into result array
resultArray.push(tempArray.splice(index, 1)[0]);
}
return resultArray;
}
Note this assumes you're using a document Class and that your buttons are already on the stage at the same y position.

AS3 HitTest between classes?

I'm gonna trying to explain as good as I can but, it's really hard to explain. I'm new to AS3 so if you are gonna help me, please help me til we solve it. Please paste code examples instead of just saying how I should do.
Ok.
On the main timeline I saying like this.
TIMER HERE THAT ADDS THE ENEMY EVERY SECOND!
var Enemy:MovieClip = new Enemy();
addChild(Enemy);
Enemy.x = 200;
Enemy.y = 200;
ANOTHER TIME THAT ADDS BULLETS EVERY .5 SECONDS!
var Bullet:MovieClip = new Bullet();
addChild(Enemy);
Bullet.x = 400;
Bullet.y = 400;
And then inside Enemy.as and Bullet.as I have code that says how it should travels, what speed etc. But how do I make a hitTest between these? I've tried to do it inside the enemy or bullet class like this.
So I basic asking for how I can hitTest two classes agianst each other? Or the object of a class?
You need to keep a reference on those enemies and bullets. Dont do var enemy:MovieClip = new Enemy(); instead do this.
var myEnemyList:Array = new Array();
var myBulletList:Array = new Array();
function Init():void{
addEventListener(Event.OnEnterFrame, Update);
}
function Update(){
//this will create a bullet and an enemy at every frame
//Create a new enemy
var enemy:Enemy = new Enemy();
myEnemyList.push(enemy); //add enemy to the array
//Create a new bullet
var enemy:Bullet = new Bullet();
myBulletlist.push(bullet);
//Update the bullets
for(var i:int=0; i < myBulletlist.length; i++){
myBulletlist[i].Update(); //you must implement this function inside your class bullet
}
//Update the enemies
for(var i:int=0; i < myEnemyList.length; i++){
myEnemyListt[i].Update(); //you must implement this function inside your class enemy
}
CheckForCollision();
}
function CheckForCollision(){
for(var i:int=0; i < myEnemyList.length; i++){
for(var j:int =0; j < myBulletList.length; j++){
if( myEnemyList[i].collidesWith(myBulletList[j]) ){
//Collision
}
}
}
}
Btw do not try to compile this its pretty much pseudo code. I'll answer questions you have. There's also a lot of tutorials everywhere on this, a little google search would help you get more specific code.

How to set dynamic locations in an Image using actionscript3.0?

I want to set different locations in an Image, and when I mouse over the location it needs to shows something('box' or 'x' nd 'y' position of the location). How can i achieve this.?
Hope, you want to set some locations in the stage and u want to store something.
If that, your coding is good. here after u can achieve that by using amf-php for back end purpose. php will help u store values in the database. refer google to know about amf-php.
good luck.
not sure wht you are looking for, may be something like that
http://www.oscartrelles.com/archives/dynamic_movieclip_registration_with_as3
Not registration point...
var msgBox:messageBox;//package
var loc:Array = new Array();
for(var i:uint = 0;i<20;i++)
{
for(var j:uint = 0;j<14;j++)
{
spr = new Sprite();
spr.graphics.beginFill(0xaaaaaa,.1);
spr.graphics.drawCircle(0,0,10);
spr.graphics.endFill();
addChild(spr);
loc.push(spr);
spr.x = 30 + i * spr.width * 1.3;
spr.y = 30 + j * spr.height * 1.3;
}
}
for(i=0; i<loc.length;i++)
{
loc[i].name = "unknown "+i;
loc[i].buttonMode = true;
loc[i].addEventListener(MouseEvent.MOUSE_OVER, mouseOverAction);
loc[i].addEventListener(MouseEvent.MOUSE_OUT, mouseOutAction);
}
function mouseOverAction (e:MouseEvent):void
{
msgBox = new messageBox(100,20,6,0xFFFFFF);
addChild(msgBox);
cur_loc_name = new TextField();
cur_loc_name.text = e.target.name;
msgBox.addChild(cur_loc_name);
cur_loc_name.x = 5;
cur_loc_name.y = 1;
msgBox.x = mouseX + 20;
msgBox.y = mouseY + 26;
}
function mouseOutAction (e:MouseEvent):void
{
removeChild(msgBox);
}
Run this code. It will fill the stage with 280 sprites, and each sprite can have diff instance name..
I wants to do this using pixels...or any other way to do?