ActionScript 3 Apparently I cannot access movieclip - actionscript-3

I've created a zoom function but when I try to scale the bg_image nothing happends. It is like I cannot access it's properties. Does anyone know why? :)
Ty!
Main class
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import fl.controls.List;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
// Zoom
public static var scale:Number = 1;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public const scaleFactor:Number = 0.8;
public var minScale:Number = 0.25;
public var maxScale:Number = 10.0;
// ------------------------
// Grafikk
public var bg_image:Sprite;
//-------------------------------
//-----------------------------------------------
public var routeArray:Array;
public var startList:List = new List();
public var sluttList:List = new List();
public var S_Norway:Dictionary = new Dictionary();
public var S_Australia:Dictionary = new Dictionary();
public var S_China:Dictionary = new Dictionary();
public var S_South_Africa:Dictionary = new Dictionary();
public var S_Brazil:Dictionary = new Dictionary();
public var S_USA:Dictionary = new Dictionary();
public var S_France:Dictionary = new Dictionary();
// ------------------------------------------------------
public static var airportDict:Dictionary = new Dictionary();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
// ---------------------------------
}
public function init(e:Event):void
{
bg_image = new Image(0, 0);
this.addChild(bg_image);
bg_image.addEventListener(MouseEvent.CLICK, mouseCoordinates);
removeEventListener(Event.ADDED_TO_STAGE, init);
// Zoom
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
private function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
trace("Minscale: ", maxScale)
trace("Returned: ", 1/scaleFactor*bg_image.scaleY)
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
private function reise(evt:MouseEvent):void
{
var new_flight:Flight = new Flight(airportDict[startList.selectedItem.label]["x"],airportDict[startList.selectedItem.label]["y"],airportDict[sluttList.selectedItem.label]["x"],airportDict[sluttList.selectedItem.label]["y"]);
bg_image.addChild(new_flight);
}
private function mouseCoordinates(event: MouseEvent):void
{
// these are the x and y relative to the object
var localMouseX:Number = bg_image.mouseX;
var localMouseY:Number = bg_image.mouseY;
trace("Local coordinates: ", localMouseX, localMouseY);
// these are the x and y relative to the whole stage
var stageMouseX:Number = event.stageX;
var stageMouseY:Number = event.stageY;
trace("Global coordinates: ", stageMouseX, stageMouseY);
}
}
}
Image class:
package {
import flash.display.Sprite;
import flash.display.MovieClip;
public class Image extends Sprite
{
public function Image(y_:Number, x_:Number)
{
this.y = y_
this.x = x_
}
}
}

You don't have minScale declared, neither maxScale.
bg_image should be declared as Sprite, otherwise Compiler Error: Implicit coercion...
`
public var bg_image:Sprite;
As your image is very small, you may want to add your listener to the stage, and not the image, it would be very dificult to click in such a small image.
Also, here is your example working with MOUSE_WHEEL, instead of Click + Ctrl / Shift
stage.addEventListener(MouseEvent.MOUSE_WHEEL, zoom);
private function zoom(mev:MouseEvent):void
{
mev.delta > 0 ?
bg_image.scaleX = bg_image.scaleY = Math.max(scaleFactor * bg_image.scaleX, minScale) :
bg_image.scaleX = bg_image.scaleY = Math.min(1/scaleFactor * bg_image.scaleX, maxScale) ;
}

Related

hitTestObject detecting collision even when there is no collision and in another case its not registering

Hello guys i am doing my University Project on this small tamogachi game where i drag and drop stuff on the char and his health or money wtv changes according to it and we had to do it with multiple classes so eveything is good except the hitTestObject if not registering properly through different classes.
Here is my code and all my project files link is also attached below please help:
Link for project files: https://drive.google.com/folderview?id=0B07PZ7vQgjsteWhVMnItczd2YUE&usp=sharing
Main Class:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
public class Main extends MovieClip {
public var addStuff:AddStuff = new AddStuff;
public var hmClass:HealthMoney = new HealthMoney;
public function Main() {
addChild(addStuff.bg);
addStuff.batMan.x = 700;
addStuff.batMan.y = 600;
addChild(addStuff.batMan);
addChild(addStuff.box);
addStuff.box.x = 1050;
addStuff.box.y = 500;
addChild(addStuff.batHealth);
addStuff.batHealth.x = 890;
addStuff.batHealth.y = 430;
addChild(addStuff.dollar);
addStuff.dollar.x = 890;
addStuff.dollar.y = 570;
addChild(addStuff.men);
addStuff.men.x = 800;
addStuff.men.y = 900;
addChild(addStuff.batBurger);
addStuff.batBurger.x = 400;
addStuff.batBurger.y = 900;
addChild(addStuff.batDrink);
addStuff.batDrink.x = 600;
addStuff.batDrink.y = 900;
addChild(addStuff.batMoney);
addStuff.batMoney.x = 850;
addStuff.batMoney.y = 940;
AddHealth();
AddMoney();
}
public function AddHealth(){
hmClass.HealthTimer();
addChild(hmClass.myHealthText);
addEventListener(Event.ENTER_FRAME,Kill);
function Kill(e:Event){
if(hmClass.health <= 0){
hmClass.batLifeTimer.stop();
addStuff.batMan.rotation -= 1;
if(addStuff.batMan.rotation <= -80){
addStuff.batMan.alpha = -5;
}
}
}
}
public function AddMoney(){
addChild(hmClass.myMoneyText);
hmClass.Money();
}
}
}
AddStuff Class:
package {
public class AddStuff{
public var bg:BG = new BG();
public var batHealth:BatHealth = new BatHealth();
public var batMan:BatMan = new BatMan();
public var batBurger:BatBurger = new BatBurger();
public var batDrink:BatDrink = new BatDrink();
public var batMoney:BatMoney = new BatMoney();
public var men:Men = new Men();
public var box:Box = new Box();
public var dollar:Dollar = new Dollar();
public function AddStuff() {
}
}
}
HealthMoney Class:
package {
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.text.TextField;
import flash.events.Event;
import flash.display.MovieClip;
import flash.text.TextFormat;
import flash.events.MouseEvent;
public class HealthMoney extends MovieClip{
public var health:int = 100;
public var money:int = 100;
public var batLifeTimer:Timer = new Timer(1000);
public var myHealthText:TextField = new TextField();
public var myHealthTextFormat:TextFormat = new TextFormat();
public var myMoneyText:TextField = new TextField();
public var myMoneyTextFormat:TextFormat = new TextFormat();
public var addStuffClass:AddStuff = new AddStuff;
public var addStuff1:AddStuff = new AddStuff;
public function HealthMoney() {
// constructor code
}
public function HealthTimer(){
myHealthText.setTextFormat(myHealthTextFormat);
myHealthTextFormat.size = 120;
myHealthTextFormat.color = 0xFFFFFF;
myHealthText.defaultTextFormat = myHealthTextFormat;
//myHealthText.border = true;
myHealthText.x = 970;
myHealthText.y = 350;
myHealthText.width = 200;
myHealthText.height = 120;
batLifeTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
health--;
//trace(health);
myHealthText.text = health.toString();
}
batLifeTimer.start();
addEventListener(Event.ENTER_FRAME, BatBurger);
function BatBurger(e:Event):void{
if(addStuff1.batMan.hitTestObject(addStuff1.batBurger)){
health++;
//trace("yo");
}
}
}
public function Money():void{
myMoneyText.setTextFormat(myMoneyTextFormat);
myMoneyTextFormat.size = 120;
myMoneyTextFormat.color = 0xFFFFFF;
myMoneyText.defaultTextFormat = myMoneyTextFormat;
myMoneyText.border = true;
myMoneyText.x = 970;
myMoneyText.y = 500;
myMoneyText.width = 500;
myMoneyText.height = 200;
//addChild(myMoneyText);
myMoneyText.text = money.toString();
addEventListener(MouseEvent.MOUSE_UP, AddMoney);
function AddMoney(e:MouseEvent):void{
if(addStuff1.batMoney.hitTestObject(addStuff1.batMan)){
myMoneyText.text = money.toString();
money = money + 100;
trace("hey");
}
}
}
}
}
and the DraggableItem Class:
(this class is the base class of all the objects i want to drag)
package {
import flash.events.MouseEvent;
import flash.display.MovieClip;
public class DraggableItem extends MovieClip{
public function DraggableItem() {
addEventListener(MouseEvent.MOUSE_DOWN, startmove);
addEventListener(MouseEvent.MOUSE_UP, stopmove);
}
public function startmove(e:MouseEvent){
this.startDrag();
}
public function stopmove(e:MouseEvent){
this.stopDrag();
}
}
}
Try this:
Main class:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.display.Stage;
public class Main extends MovieClip {
public static var stageRef:Stage;
public var addStuff:AddStuff = new AddStuff;
public var hmClass:HealthMoney;
public function Main() {
stageRef = stage;
addChild(addStuff.bg);
addStuff.batMan.x = 700;
addStuff.batMan.y = 600;
addChild(addStuff.batMan);
addChild(addStuff.box);
addStuff.box.x = 1050;
addStuff.box.y = 500;
addChild(addStuff.batHealth);
addStuff.batHealth.x = 890;
addStuff.batHealth.y = 430;
addChild(addStuff.dollar);
addStuff.dollar.x = 890;
addStuff.dollar.y = 570;
addChild(addStuff.men);
addStuff.men.x = 800;
addStuff.men.y = 900;
addChild(addStuff.batBurger);
addStuff.batBurger.x = 400;
addStuff.batBurger.y = 900;
addChild(addStuff.batDrink);
addStuff.batDrink.x = 600;
addStuff.batDrink.y = 900;
addChild(addStuff.batMoney);
addStuff.batMoney.x = 850;
addStuff.batMoney.y = 940;
hmClass = new HealthMoney(addStuff);
AddHealth();
AddMoney();
}
public function AddHealth(){
hmClass.HealthTimer();
addChild(hmClass.myHealthText);
addEventListener(Event.ENTER_FRAME,Kill);
function Kill(e:Event){
if(hmClass.health <= 0){
hmClass.batLifeTimer.stop();
addStuff.batMan.rotation -= 1;
if(addStuff.batMan.rotation <= -80){
addStuff.batMan.alpha = -5;
}
}
}
}
public function AddMoney(){
addChild(hmClass.myMoneyText);
hmClass.Money();
}
}
}
HealthMoney class:
package {
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.text.TextField;
import flash.events.Event;
import flash.display.MovieClip;
import flash.text.TextFormat;
import flash.events.MouseEvent;
public class HealthMoney extends MovieClip{
public var health:int = 100;
public var money:int = 100;
public var batLifeTimer:Timer = new Timer(1000);
public var myHealthText:TextField = new TextField();
public var myHealthTextFormat:TextFormat = new TextFormat();
public var myMoneyText:TextField = new TextField();
public var myMoneyTextFormat:TextFormat = new TextFormat();
public var addStuffClass:AddStuff = new AddStuff;
public var addStuff1:AddStuff;
public function HealthMoney(addStuff:AddStuff) {
this.addStuff1 = addStuff;
}
public function HealthTimer(){
myHealthText.setTextFormat(myHealthTextFormat);
myHealthTextFormat.size = 120;
myHealthTextFormat.color = 0xFFFFFF;
myHealthText.defaultTextFormat = myHealthTextFormat;
//myHealthText.border = true;
myHealthText.x = 970;
myHealthText.y = 350;
myHealthText.width = 200;
myHealthText.height = 120;
batLifeTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
health--;
//trace(health);
myHealthText.text = health.toString();
}
batLifeTimer.start();
addEventListener(Event.ENTER_FRAME, BatBurger);
function BatBurger(e:Event):void{
if(addStuff1.batMan.hitTestObject(addStuff1.batBurger)){
health++;
//trace("yo");
}
}
}
public function Money():void{
myMoneyText.setTextFormat(myMoneyTextFormat);
myMoneyTextFormat.size = 120;
myMoneyTextFormat.color = 0xFFFFFF;
myMoneyText.defaultTextFormat = myMoneyTextFormat;
myMoneyText.border = true;
myMoneyText.x = 970;
myMoneyText.y = 500;
myMoneyText.width = 500;
myMoneyText.height = 200;
//addChild(myMoneyText);
myMoneyText.text = money.toString();
Main.stageRef.addEventListener(MouseEvent.MOUSE_UP, AddMoney);
function AddMoney(e:MouseEvent):void{
if(addStuff1.batMoney.hitTestObject(addStuff1.batMan)){
myMoneyText.text = money.toString();
money = money + 100;
trace("hey");
}
}
}
}
}
The line "public static var stageRef:Stage;" creates a static variable of the type Stage. Static variables are accessible from other classes without needing an instance of the class.
The line "stageRef = stage" basically sets the value of stageRef to stage. You access the stageRef by simply writing "Main.stageRef". You need a instance of the stage because of the line "Main.stageRef.addEventListener(MouseEvent.MOUSE_UP, AddMoney);" in the HealthMoney class. The mouse_up event will not work properly if you only write "addEventListener(MouseEvent.MOUSE_UP, AddMoney);", since the focus is on the stage.
The line "hmClass = new HealthMoney(addStuff);" sends the instance of the AddStuff class to the HealthMoney constructor. You need to do that because if you write "addStuff1 = new AddStuff", you will create a new instance of AddStuff, and the new instance of AddStuff does not have the movieclips you added in the main class, which will make the hittestobject not triggering.

AS3. How can a global var take a value which appears in a listener Event.COMPLETE

This is my code:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.LoaderInfo;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.GradientType;
import flash.sampler.getSize;
public class Miniaturka extends MovieClip {
private var id:String;
public static var miniWidth:Number = 0;
private var tween:Tween;
private var tryb:Boolean;
private var button:Sprite;
private var index:Number;
private var aktywna:Boolean = false;
public var bLoad:Boolean = false;
public function Miniaturka(id:String,index:Number):void {
this.id = id;
this.index = index;
tryb = false;
var loader:Loader = new Loader();
loader.load(new URLRequest("images/"+id+"m.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,nLoadComplete);
this.alpha = 1;
button = new Sprite();
button.graphics.beginFill(0x000000,0);
button.graphics.drawRect(0,0,889,500);
button.graphics.endFill();
button.buttonMode = true;
addChild(button);
button.addEventListener(MouseEvent.MOUSE_OVER,onOver);
button.addEventListener(MouseEvent.MOUSE_OUT,onOut);
button.addEventListener(MouseEvent.CLICK,onClick);
}
private function nLoadComplete(event:Event):void {
var loader:Loader = new Loader();
loader = LoaderInfo(event.target).loader;
pusty.addChild(loader);
ladowanie.visible = false;
tween = new Tween(pusty,"alpha",Regular.easeOut,0,0.6,2,true);
bLoad = true;
setStan(false);
miniWidth = loader.width;
pusty.alpha = 0;
}
private function onOver(event:MouseEvent):void {
if (!aktywna) {
setStan(true);
}
}
private function onOut(event:MouseEvent):void {
if (!aktywna) {
setStan(false);
}
}
private function onClick(event:MouseEvent):void {
aktywuj();
}
public function deaktywuj():void {
setStan(false);
aktywna = false;
}
public function aktywuj():void {
MovieClip(parent).deaktywuj();
aktywna = true;
setStan(true);
MovieClip(parent.parent).loadBig(id,index);
}
private function setStan(tryb:Boolean):void {
this.tryb = tryb;
if (tryb) {
pusty.alpha = 1;
} else {
pusty.alpha = 0.6;
}
}
}
}
I want to create a gallery, and this is a code of a class which loads jpg. files with different widths, but the same height.
My problem is that I want to make the public static var miniWidth which takes the value: loader.width in function: nLoadComplete, take that value as a global var, and put it in the line: button.graphics.drawRect(0,0,889,500); so it would look like button.graphics.drawRect(0,0,miniWidth ,500);
This will create a button(rectangle) the same height and width as the loaded jpg. but i can't figure it out... How can I do that?
Wait for the image to load before drawing your shape. In the example below, I've only reprinted the affected functions.
private function Miniaturka(id:String, index:Number):void {
this.id = id;
this.index = index;
tryb = false;
var loader:Loader = new Loader();
loader.load(new URLRequest("images/" + id + "m.jpg"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, nLoadComplete);
this.alpha = 1;
}
private function nLoadComplete(event:Event):void {
var loader:Loader = new Loader();
loader = LoaderInfo(event.target).loader;
pusty.addChild(loader);
ladowanie.visible = false;
tween = new Tween(pusty, "alpha", Regular.easeOut, 0, 0.6, 2, true);
bLoad = true;
setStan(false);
miniWidth = loader.width;
pusty.alpha = 0;
createBtn();
}
private function createBtn():void {
button = new Sprite();
button.graphics.beginFill(0x000000, 0);
button.graphics.drawRect(0, 0, miniWidth, 500);
button.graphics.endFill();
button.buttonMode = true;
addChild(button);
button.addEventListener(MouseEvent.MOUSE_OVER, onOver);
button.addEventListener(MouseEvent.MOUSE_OUT, onOut);
button.addEventListener(MouseEvent.CLICK, onClick);
}

Error 1046:Type not found or was not a compile-time constant:Listing2

I am trying to add a movieclip that is generated through a loop from SearchVectorTest class file, and put that into sresultnologin class file. Then i will make that movieclip clickable, and when clicked, goes to next class,display a new stage, pull the information from that specific stored in that movieclip, and pull the rest of the information from the database and display them.
I am having an error at the moment, Type not found. I can't seem to add the Movieclip(box) as a button. on this line var newListing:Listing2 = Bolder.getChildAt(0);
sresultnologin.as
package com.clark
{
import com.clark.SearchVectorTest;
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Stage;
import fl.controls.Button;
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class sresultnologin extends MovieClip {
public var s1:Searchreult = new Searchreult ();
public function sresultnologin(){
// init
addEventListener(Event.ADDED_TO_STAGE, onadded);
function onadded (event:Event):void{
s1.x=-10;
s1.y=10;
addChild(s1);
}
var s3:SearchVectorTest= new SearchVectorTest(new Vector.<searchVO1>);
addChild (s3);
s1.SRhome.addEventListener(MouseEvent.CLICK, fl_ClickToGoTol);
s1.ARsearch.addEventListener(MouseEvent.CLICK, fl_ClickToGosearch);
if( s3.listings.length > 0 )
{
// get the first listing in the listing array
var newListing:Listing8 = s3.listings[0];
newListing.addEventListener(MouseEvent.CLICK, gotoscener);
}
else
{
}
}
// private methods
private function gotoscener(event:MouseEvent):void
{
var s9:Listingdetail = new Listingdetail ();
removeChild(s1);
addChild(s9);
}
private function fl_ClickToGoTol(event:MouseEvent):void
{
var s9:Account = new Account ();
removeChild(s1);
addChild(s9);
}
private function fl_ClickToGosearch(event:MouseEvent):void
{
var s9:searchVO1 = new searchVO1 ();
removeChild(s1);
addChild(s9);
}
}
}
SearchVectorTest.as
package com.clark
{
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class SearchVectorTest extends MovieClip
{
public var listings:Vector.<Listing8>;
public function SearchVectorTest(test:Vector.<searchVO1>)
{
for (var j:int = 0; j < test.length; j++)
{
trace(test[j].nobed);
trace(test[j].zip);
trace(test[j].Location);
trace(test[j].price);
}
var len:int = test ? test.length : 0;
// create your vector for your listings with the len size
listings = new Vector.<Listing8>(len, true);
var currentY:int = 200;
for (var k:int = 0; k < test.length; k++)
{
var Bolder:Listing8 = new Listing8();
Bolder.x=20;
var bf:TextField = new TextField();
var bf1:TextField = new TextField();
var bf2:TextField = new TextField();
var bf3:TextField = new TextField();
bf3.width = 100;
bf.defaultTextFormat = new TextFormat("Arial", 12, 0, null, null, null, null, null, TextFormatAlign.CENTER);
bf.width = 100;
bf.autoSize = TextFieldAutoSize.CENTER;
bf1.width = 100;
bf1.autoSize = TextFieldAutoSize.CENTER;
bf2.autoSize = TextFieldAutoSize.CENTER;
bf3.autoSize = TextFieldAutoSize.CENTER;
bf3.width = 100;
bf1.y= bf.height+5;
bf.text = test[k].nobed;
bf1.text = test[k].zip;
bf2.text = test[k].Location;
bf3.text = test[k].price;
bf.x = (Bolder.height-bf.height)*.2
Bolder.addChild(bf);
Bolder.addChild(bf1);
Bolder.addChild(bf2);
Bolder.addChild(bf3);
Bolder.properties = test[k].nobed;
Bolder.properties = test[k].zip;
// position the object based on the accumulating variable.
Bolder.y = currentY;
addChild(Bolder);
Bolder.mouseChildren = false; // ignore children mouseEvents
Bolder.mouseEnabled = true; // enable mouse on the object - normally set to true by default
Bolder.useHandCursor = true; // add hand cursor on mouse over
Bolder.buttonMode = true;
listings[k] = Bolder;
currentY += Bolder.height + 10;
}
}
}
}
SearchVO1
package com.clark
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Stage;
import fl.controls.Button;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLLoaderDataFormat;
import flash.net.URLVariables;
import flash.utils.*;
import flash.sampler.NewObjectSample;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
public class searchVO1 extends MovieClip {
private var Arvariables:URLVariables;
private var SrSend:URLRequest;
private var SaLoader:URLLoader;
public var nobed:String;
public var zip:String;
public var Location:String;
public var price:String;
public var callMethod:Function;
public var s1:searchpage = new searchpage ();
public function searchVO1():void{
addEventListener(Event.ADDED_TO_STAGE, onadded); // init
function onadded (event:Event):void{
s1.x=-10;
s1.y=10;
addChild(s1);
s1.account.addEventListener(MouseEvent.CLICK, fl_ClickToGoToaccount);
s1.searchs.addEventListener(MouseEvent.CLICK, ValidateAndsearch);
s1.Au.addEventListener(MouseEvent.CLICK, fl_ClickToGoToautomatch);
s1.setting.addEventListener(MouseEvent.CLICK, fl_ClickToGoToss);
s1.Shome.addEventListener(MouseEvent.CLICK, fl_ClickToGoTohom);
// Build the varSend variable
SrSend = new URLRequest("http://localhost/search.php");
SrSend.method = URLRequestMethod.POST;
Arvariables = new URLVariables;
SrSend.data = Arvariables;
SaLoader = new URLLoader();
SaLoader.dataFormat = URLLoaderDataFormat.TEXT;
SaLoader.addEventListener(Event.COMPLETE,Asandler);
// private methods
function Asandler(event:Event):void{
// retrieve data from php call
var resultString :String = event.target.data;
// parse result string as json object and cast it to array
var resultArray :Array = JSON.parse( resultString ) as Array;
// get the length of the result set
var len:int = resultArray.length;
// create vector of SearchVO
var searchVOs:Vector.<searchVO1> = new Vector.<searchVO1>();
// loop the result array
var i:int;
for(i=0; i<len; i++ )
{
searchVOs[i] = new searchVO1();
searchVOs[i].nobed = resultArray[i].nobed;
searchVOs[i].zip = resultArray[i].zip;
searchVOs[i].Location = resultArray[i].Location;
searchVOs[i].price = resultArray[i].price;
}
// call a function to create your boxes
// or maybe create your SearchVector class and pass it your search vector
var mySearchVector:SearchVectorTest = new SearchVectorTest(searchVOs);
addChild(mySearchVector);
}
}
}
public function searchVOs( nobed:String, zip:String, location:String, price:String )
{
this.nobed = nobed;
this.zip = zip;
this.Location = Location;
this.price = price;
}
public function ValidateAndsearch (event:MouseEvent):void {
// validate fields
Arvariables.nobed = s1.nobed.text;
Arvariables.zip = s1.zip.text;
Arvariables.Location = s1.Location.text;
Arvariables.price = s1.price.text;
SaLoader.load(SrSend);
var s7:sresultnologin = new sresultnologin()
removeChild(s1);
addChild(s7);
}
// close else condition for error handling
// close validate and send function
private function fl_ClickToGoToautomatch(event:MouseEvent):void
{
var s7:Auto = new Auto ();
removeChild(s1);
addChild(s7);
}
private function fl_ClickToGoToss(event:MouseEvent):void
{
//
}
private function fl_ClickToGoToaccount(event:MouseEvent):void
{
var s7:Account = new Account ();
removeChild(s1);
addChild(s7);
}
private function fl_ClickToGoTohom(event:MouseEvent):void
{
var s7:homepage = new homepage ();
removeChild(s1);
addChild(s7);
}
}
}
i think you have to remove these lines:
public var Bolder:MovieClip;
public var Listing2:MovieClip;
and try to get your Listing2 object like this:
var newListing:Listing2 = s3.getChildAt(0);
but if you want to access your listings in the SearchVectorTest class it's better to keep a public reference of them like this (maybe in an array or a vector):
SearchVectortest class:
public class SearchVectorTest extends MovieClip
{
/** the array of listings **/
public var listings:Vector.<Listing2>;
public function SearchVectorTest(test:Vector.<searchVO1>)
{
// put the array length in a variable -> if test = null make len = 0
var len:int = test ? test.length : 0;
// create your vector for your listings with the len size
listings = new Vector.<Listing2>(len, true);
// ...
for( var k:int = 0; k < len; k++ )
{
var bolder:Listing2 = new Listing2();
bolder.mouseChildren = false; // ignore children mouseEvents
bolder.mouseEnabled = true; // enable mouse on the object - normally set to true by default
bolder.useHandCursor = true; // add hand cursor on mouse over
bolder.buttonMode = true; // this must be set to true to have hand cursor
// add your linsting to the vector
listings[k] = bolder;
//...
}
// ...
}
}
after that you could get your listing like this:
sresultnologin.as
public class sresultnologin extends MovieClip
{
public var s1 :Searchreult = new Searchreult ();
//public var Bolder :MovieClip; // never used -> useless
//public var Listing2 :MovieClip; // never used -> useless
public function sresultnologin()
{
// init
addEventListener(Event.ADDED_TO_STAGE, onadded);
function onadded (event:Event):void
{
s1.x=-10;
s1.y=10;
addChild(s1);
}
var s3:SearchVectorTest= new SearchVectorTest(new Vector.<searchVO1>);
addChild (s3);
s1.SRhome.addEventListener(MouseEvent.CLICK, fl_ClickToGoTol);
s1.ARsearch.addEventListener(MouseEvent.CLICK, fl_ClickToGosearch);
// verify if there are enties in the array
if( s3.listings.length > 0 )
{
// get the first listing in the listing array
var newListing:Listing2 = s3.listings[0];
newListing.addEventListener(MouseEvent.CLICK, goto);
}
else
{
// do something if there are no results
}
}
//...
}
hope that helps ;)

As3 & Flex Builder: Flickr API Photo Application

My problem is when I run the application, the photos show up fine, but they pop up only in a single row. I'm trying to get at least 20 rows on the application. Also, how would I code the button function (searchNow) to take whatever tags that is entered inside of the search bar to display the right images?
{
//===================
//ini variables
//===================
import flash.display.Loader;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.sensors.Accelerometer;
import flash.system.Security;
import flash.text.TextField;
import libs.flickrviewer_mc;
Security.allowDomain("*", "api.flickr.com");
import flash.display.Bitmap;
public class FlickrViewer extends libs.flickrviewer_mc
{
//===================
//ini variables
//===================
private var tag:String;
//===================
//ini variables
//===================
private var xpos:Number = 0;
private var ypos:Number = 0;
private var dif:Number = 150;
private var totalCols:int = 10;
private var count:int = 0;
private var i:int = 0;
private var squares_arr:Array = [];
//===================
//flickr variables
//===================
private var key:String = "Key Goes Here"; //your flickr api key
private var per_page:int = 5;
private var page:int = 1;
private var xml_url:String = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="+key+"&tags="+tag+"&per_page="+per_page+"&page="+page;
//===================
//XML
//===================
private var pics:XML = new XML();
private var pics_url:URLRequest = new URLRequest(xml_url);
private var picsLoader:URLLoader = new URLLoader(pics_url);
//===================
//flickr variables
//===================
private var photo_id:String;
private var photo_owner:String;
private var photo_url:String = "http://www.flickr.com/photos/";
public function FlickrViewer()
{
super();
trace("yo");
this.picsLoader.addEventListener(Event.COMPLETE, picsLoaded);
this.back_btn.addEventListener(MouseEvent.CLICK, goBack);
this.searchFlickr_btn.addEventListener(MouseEvent.CLICK, searchNow);
//this.buttonMode = true;
}
private function searchNow(e:Event):void
{
var url:String = photo_url+"/"+photo_owner+"/"+photo_id;
var req:URLRequest = new URLRequest(url);
(req, "_blank");
}
private function loadImage(img_src:String):void
{
var loader:Loader = new Loader();
var img_url:String = img_src;
var request_url:URLRequest = new URLRequest(img_url);
loader.load(request_url);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener);
}
private function progressListener(e:ProgressEvent):void
{
var bl:int = e.bytesLoaded;
var bt:int = e.bytesTotal;
var percent:int = Math.ceil((bl*100)/bt);
}
private function completeListener(e:Event):void
{
var img:Bitmap = e.currentTarget.content;
trace(img.width);
img.x=34 + (count * 90);
img.y=110;
img.width = img.height = 75;
this.addChild(img);
count++;
}
private function picsLoaded(e:Event):void
{
pics = XML(picsLoader.data);
var stat:String = pics.#stat.toString();
var totalPages:int = pics.photos.#pages;
var totalPics:int = pics.photos.#total;
trace("bob",pics);
trace("status: "+stat);
trace("Total pages: "+totalPages);
trace("Total pics: "+totalPics);
trace("-=-=-=-=-=-=-=-=-=-=-=");
var allPics:XMLList = pics.photos.*;
//loadImage(allPics[0]);
for each (var photo:XML in allPics)
{
var pic_src:String = "http://farm"+photo.#farm+".static.flickr.com/"+photo.#server+"/"+photo.#id+"_"+photo.#secret+"_m.jpg";
trace("title: "+photo.#title+" owner: "+photo.#owner);
trace("Source: "+pic_src);
trace("-=-=-=-=-=-=-=-=-=-=-=");
trace(pic_src)
var newName:String = "square_"+i;
loadImage(pic_src);
}
}
//===================
//back button event
//===================
private function goBack(e:MouseEvent):void
{
}
}
}

actionscript 3 new game btn in main menu not working

I have a problem with my game.
When i played level 1 and i return to my main menu, the button new game doesn't work anymore.
Does anyone know what could be the problem?
this is what i have in my main menu as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import HomeTitel;
import InstBtn;
import NieuwBtn;
public class Hoofdmenu extends MovieClip
{
private var homeTitel:HomeTitel;
private var instBtn:InstBtn;
private var nieuwBtn:NieuwBtn;
private var inst:Instructions;
private var level1:Level1;
public function Hoofdmenu():void
{
placeHomeTitel();
placeInstructionsBtn();
placeNieuwBtn();
}
private function placeHomeTitel():void
{
homeTitel = new HomeTitel();
addChild(homeTitel);
homeTitel.x = 275;
homeTitel.y = 20;
}
private function placeInstBtn():void
{
instBtn = new InstBtn();
addChild(instBtn);
instBtn.x = 275;
instBtn.y = 225;
instBtn.addEventListener(MouseEvent.CLICK, gotoInstructions);
}
private function gotoInstructions(event:MouseEvent)
{
inst = new Instructoins();
addChild(inst);
}
private function placeNewBtn():void
{
newBtn = new NewBtn();
addChild(newBtn);
newBtn.x = 275;
newBtn.y = 175;
newBtn.addEventListener(MouseEvent.CLICK, gotoLevel1);
}
private function gotoLevel1(event:MouseEvent):void
{
level1 = new Level1();
addChild(level1);
}
}
}
this is what i have in my level1 as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import L1Achtergrond;
import L1Titel;
import MenuBtn;
import Sun;
import Min;
import GameOver;
import WellDone;
import VolgLevel;
import HoofdmenuBtn;
import Opnieuw;
public class Level1 extends MovieClip
{
private var back:L1Achtergrond;
private var titel:L1Titel;
private var menu:MenuBtn;
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
private var sunArray:Array = new Array();
private var timer:Timer;
private var min:Min;
private var gameover:GameOver;
private var welldone:WellDone;
private var volglevel:VolgLevel;
private var opn:Opnieuw;
private var hoofdBtn:HoofdmenuBtn;
private var level1:Level1;
private var level2:Level2;
private var hoofdmenu:Hoofdmenu;
public function Level1():void
{
back = new L1Achtergrond();
addChild(back);
placeTitel();
timer = new Timer(3000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, startLevel1);
timer.start();
}
private function placeTitel():void
{
titel = new L1Titel();
addChild(titel);
titel.x = 275;
titel.y = 150;
}
private function startLevel1(event:TimerEvent):void
{
for (counter = 0; counter < aantalSun; counter++)
{
sun = new Sun();
sunArray.push(sun);
addChild(sun);
sun.addEventListener(MouseEvent.CLICK, checkSun);
}
min = new Min();
addChild(min);
min.x = 275;
min.y = 30;
min.play();
min.width = 40;
min.height = 20;
timer = new Timer(20000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, gameOver);
timer.start();
menu = new MenuBtn();
addChild(menu);
menu.x = 510;
menu.y = 380;
menu.addEventListener(MouseEvent.CLICK, gotoHoofdmenu);
}
private function checkSun(event:MouseEvent):void
{
aantalSun--;
if (aantalSun == 0)
{
wellDone();
timer.stop();
}
}
public function wellDone():void
{
removeChild(menu);
removeChild(min);
welldone = new WellDone();
addChild(welldone);
welldone.x = 275;
welldone.y = 150;
volglevel = new VolgLevel();
addChild(volglevel);
volglevel.x = 300;
volglevel.y = 250;
volglevel.addEventListener(MouseEvent.CLICK, gotoLevel2);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuW);
}
private function gameOver(event:TimerEvent):void
{
//timer.stop();
removeChild(min);
removeChild(menu);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
gameover = new GameOver();
addChild(gameover);
gameover.x = 275;
gameover.y = 150;
opn = new Opnieuw();
addChild(opn);
opn.x = 300;
opn.y = 250;
opn.addEventListener(MouseEvent.CLICK, level1Opn);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuG);
}
private function level1Opn(event:MouseEvent):void
{
removeChild(gameover);
removeChild(opn);
removeChild(hoofdBtn);
removeChild(back);
level1 = new Level1();
addChild(level1);
}
private function gotoHoofdmenu(event:MouseEvent):void
{
timer.stop();
removeChild(min);
removeChild(menu);
removeChild(back);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
}
private function gotoHoofdmenuW(event:MouseEvent):void
{
removeChild(back);
removeChild(welldone);
removeChild(hoofdBtn);
removeChild(volglevel);
}
private function gotoHoofdmenuG(event:MouseEvent):void
{
removeChild(back);
removeChild(gameover);
removeChild(hoofdBtn);
removeChild(opn);
}
private function gotoLevel2(event:MouseEvent):void
{
removeChild(back);
removeChild(volglevel);
removeChild(hoofdBtn);
removeChild(welldone);
level2 = new Level2();
addChild(level2);
}
}
}
I think you should rebuild/redesign the structure of your game.
Now, your code does few strange things:
in your Main class: everytime you call function gotoLevel1 you create a new instance of Level1
in your Level1 class in the function level1Opn you create another instance of 'Level1' and you add it inside Level1 - quite a mess.
This isn't just small code tweak - you should rebuild it quite significantly.
Seems like you never remove level1 from your menu. Even though you remove all children from Level 1, the movieclip will still exist and be on top of your menu.
I would recommend reading though this tutorial, as it will teach you some basic skills about structuring your code, and specific game development features (sound, preloading, saving things in cookies): http://gamedev.michaeljameswilliams.com/2008/09/17/avoider-game-tutorial-1/