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/
Related
Making a map creation program. Field.as instantiates _player. Player.as addsChild _editorPanel to parent. EditorPanel.as instantiates a movieclip called tilepalette when I click a button in the editor panel. Tilepalette holds all of my tilesets that I want to be able to choose a tile from by clicking the tile that I want.
Field.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.display.FrameLabel;
import flash.display.DisplayObjectContainer;
import flash.geom.Rectangle;
public class Field extends MovieClip{
private var player:Player;
private var sampleTile:Tile = new Tile();
private var _tilePalette:TilePalette;
private var _paletteArray:Array = [];
public function Field()
{
player = new Player();
player.x = 0;
player.y = 0;
addChild(player);
GetSampleTiles();
}
private function GetSampleTiles()
{
for (var i:int = 1; i <= sampleTile.totalFrames; i++)
{
var tileObj:Object = new Object();
sampleTile.gotoAndStop(i);
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(sampleTile);
tileObj.Name = sampleTile.currentFrameLabel;
tileObj.Graphic = graphicData;
tileObj.Frame = sampleTile.currentFrame;
Engine._tilesData.push(tileObj);
}
}
}
}
Player.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class Player extends MovieClip
{
private var _inp:Input = new Input();
private var _playerXindex:int = 0;
private var _playerYindex:int = 0;
private var _heldTile:Object;
private var _editorPanel:EditorPanel;
public function Player()
{
addChild(_inp);
addEventListener(Event.ENTER_FRAME, HandleKeys);
_heldTile = new Object();
}
private function HandleKeys(e:Event)
{
_playerXindex = x/32;
_playerYindex = y/32;
if(_inp.keyUp)
{
y -= 32;
}
if(_inp.keyDown)
{
y += 32;
}
if(_inp.keyLeft)
{
x -= 32;
}
if(_inp.keyRight)
{
x += 32;
}
if(_inp.keySpace)
{
try{DrawATile(_heldTile);}
catch(err:Error){trace("Bad or no graphic. Using this instead.");}
finally{DrawATile(Engine._tilesData[0]);}
}
if(_inp.keyA)
{
trace(Engine.tileObjIndex[_playerYindex][_playerXindex].Name);
}
if(_inp.keyB)
{
BuildStarterIndex();
SetHeldTile(Engine._tilesData[0]);
}
}
private function DrawATile(tileToDraw:Object)
{
if (Engine.tileObjIndex[_playerYindex][_playerXindex].Name.indexOf("Placeholder") >= 0)
{
trace("set");
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(tileToDraw.Graphic);
Engine.tileObjIndex[_playerYindex][_playerXindex].Name = tileToDraw.Name;
Engine.tileObjIndex[_playerYindex][_playerXindex].Graphic = tileToDraw.Graphic;
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = x;
newTile.y = y;
parent.addChild(newTile);
}
}
private function BuildStarterIndex()
{
_editorPanel = new EditorPanel();
_editorPanel.x = 1;
_editorPanel.y = 544;
parent.addChild(_editorPanel);
for (var i:int = 0; i < 20; i++)
{
Engine.tileObjIndex[i] = [];
for (var u:int = 0; u < 20; u++)
{
var tileObj:Object = new Object();
var graphicData:BitmapData = new BitmapData(32,32);
graphicData.draw(Engine._tilesData[0].Graphic);
tileObj.Name = "Placeholder" + "["+i+"]"+"["+u+"]";
tileObj.Graphic = graphicData;
tileObj.Frame = 0;
Engine.tileObjIndex[i].push(tileObj);
}
}
}
private function SetHeldTile(tiletoset:Object)
{
_heldTile.Name = tiletoset.Name;
_heldTile.Graphic = tiletoset.Graphic;
_heldTile.Frame = tiletoset.Frame;
_editorPanel.tileName.text = _heldTile.Name;
_editorPanel.tileFrame.text = _heldTile.Frame;
var heldTile:Bitmap = new Bitmap(_heldTile.Graphic);
heldTile.x = 30;
heldTile.y = 31;
_editorPanel.addChild(heldTile);
}
}
}
EditorPanel.as:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Bitmap;
import flash.events.Event;
public class EditorPanel extends MovieClip
{
public var _tilePalette:TilePalette;
private var _pArray:Array = [];
private var _mouseXi:int;
private var _mouseYi:int;
public var _tileGrabbed:Object;
public function EditorPanel()
{
btnpalette.addEventListener(MouseEvent.CLICK, BuildPalette);
}
private function UpdateMouse(e:Event)
{
_mouseXi = Math.floor(_tilePalette.mouseX/32);
_mouseYi = Math.floor(_tilePalette.mouseY/32);
}
private function BuildPalette(e:MouseEvent)
{
_tilePalette = new TilePalette();
_tilePalette.x = mouseX;
_tilePalette.y = mouseY-256;
addChild(_tilePalette);
var counter:int = 1;
for (var i:int = 0; i < 8; i++)
{
_pArray[i] = [];
for(var u:int = 0; u < 8; u++)
{
if(counter >= Engine._tilesData.length)
{
counter = 1;
}
var b:Bitmap = new Bitmap(Engine._tilesData[counter].Graphic);
b.x = 32 * u;
b.y = 32 * i;
_tilePalette.addChild(b);
_pArray[i].push(Engine._tilesData[counter]);
counter++;
}
}
_tilePalette.addEventListener(MouseEvent.MOUSE_MOVE, UpdateMouse);
_tilePalette.addEventListener(MouseEvent.CLICK, GrabATile);
}
private function GrabATile(e:MouseEvent)
{
return _pArray[_mouseXi][_mouseYi];
}
}
}
The problem is that when I do GrabATile, I don't know what to do with the returned Object reference. I want to use that Object in the Player function SetHeldTile.
So this will make it work, but I would suggest looking to refactor that code a bit. Adding children that add things to their parents is not the best design... There is also round robin stuff going on there where the editor selects the tile, but then the player sets things like tileName back on the editor after it is told about the new tile. This should occur in the editor where tile selection occurs etc.
That said, depending on your flow, here is how to make it work:
EditorPanel already has a property _tileGrabbed. so in your GrabATile() method just set
_tileGrabbed = _pArray[_mouseXi][_mouseYi];
Then in your setHeldTile() method... simply say
_heldTile = _editorPanel._tileGrabbed.
Now, if you need GrabATile() to TRIGGER setHeldTile(), the best way to handle that would be with an event.
// in EditorPanel
private function GrabATile(e:MouseEvent){
_tileGrabbed = _pArray[_mouseXi][_mouseYi];
dispatchEvent(new Event("tileChanged"));
}
// in Player
private function BuildStarterIndex(){
_editorPanel = new EditorPanel();
_editorPanel.addEventListener("tileChanged", setHeldTile);
// ... rest of code
}
private function SetHeldTile(event:Event){
_heldTile = _editorPanel._tileGrabbed;
// ... rest of code
}
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.
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) ;
}
i make a class like this:
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Hint extends Sprite
{
public static var _instance:Hint = null;
public function Hint()
{
_instance = this;
}
public function DrawHintText():void
{
Const._scoreText = new TextField();
Const._scoreTextHolder = new TextField();
Const._highScoreText = new TextField();
Const._highScoreTextHolder = new TextField();
Const._timeLeft = new TextField();
Const._timeLeftHolder = new TextField();
Const._scoreTextHolder.textColor = 0xFFFFFF;
Const._scoreTextHolder.x = stage.stageWidth - 350;
Const._scoreTextHolder.y = 100;
Const._scoreTextHolder.text = "Score: ";
Const._scoreTextHolder.selectable = false;
Const._scoreText.textColor = 0xFFFFFF;
Const._scoreText.x = stage.stageWidth - 250;
Const._scoreText.y = 100;
Const._scoreText.text = "--";
Const._scoreText.selectable = false;
Const._highScoreTextHolder.textColor = 0xFFFFFF;
Const._highScoreTextHolder.x = stage.stageWidth - 350;
Const._highScoreTextHolder.y = 150;
Const._highScoreTextHolder.text = "High Score: ";
Const._highScoreTextHolder.selectable = false;
Const._highScoreText.textColor = 0xFFFFFF;
Const._highScoreText.x = stage.stageWidth - 250;
Const._highScoreText.y = 150;
Const._highScoreText.text = "--";
Const._highScoreText.selectable = false;
Const._timeLeftHolder.textColor = 0xFF0000;
Const._timeLeftHolder.x = stage.stageWidth - 350;
Const._timeLeftHolder.y = 200;
Const._timeLeftHolder.text = "Time Left: ";
Const._timeLeftHolder.selectable = false;
Const._timeLeft.textColor = 0xFF0000;
Const._timeLeft.x = stage.stageWidth - 275;
Const._timeLeft.y = 200;
Const._timeLeft.text = "00:00";
Const._timeLeft.selectable = false;
addChild(Const._scoreText);
addChild(Const._scoreTextHolder);
addChild(Const._highScoreText);
addChild(Const._highScoreTextHolder);
addChild(Const._timeLeft);
addChild(Const._timeLeftHolder);
}
}
}
and i called on the GameManager:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
[SWF(width='1366',height='768',backgroundColor='#000000',frameRate='30')]
public class GameManager extends Sprite
{
public function GameManager():void
{
DrawHintText();
GenerateField();
ShowField();
GenerateGems();
}
private function GenerateField():void
{
Const._gridField = new Array();
for (var i:uint = 0; i < Const._gridSizeY; i++)
{
Const._gridField[i] = new Array();
for (var j:uint = 0; j < Const._gridSizeX; j++)
{
Const._gridField[i][j] = 0;
}
}
}
private function ShowField():void
{
Const._fieldSprite = new Sprite();
addChild(Const._fieldSprite);
Const._fieldSprite.graphics.lineStyle(1, 0xFFFFFF);
for (var i:uint = 0; i < Const._gridSizeY; i++)
{
for (var j:uint = 0; j < Const._gridSizeX; j++)
{
Const._fieldSprite.graphics.beginFill(0x666666);
Const._fieldSprite.graphics.drawRect(25 + 65 * j, 80 + 60 * i, 65, 60);
Const._fieldSprite.graphics.endFill();
}
}
}
private function DrawHintText():void
{
Hint._instance.DrawHintText();
}
private function GenerateGems():void
{
}
}
}
and here is the Const:
package
{
import flash.display.Sprite;
import flash.text.TextField;
public class Const
{
public static var _gridField:Array;
public static var _fieldSprite:Sprite;
public static var _scoreText:TextField;
public static var _scoreTextHolder:TextField;
public static var _highScoreText:TextField;
public static var _highScoreTextHolder:TextField;
public static var _timeLeft:TextField;
public static var _timeLeftHolder:TextField;
public static const _gridSizeX:Number = 10;
public static const _gridSizeY:Number = 10;
public function Const()
{
}
}
}
when i run the code, i got the error:
Where do i miss some code?
Invoking function DrawHintText() in Hint._instance.DrawHintText(); doesn't create instance of class Hint.
Try to substite your public variable with public getter.
private static var __instance:Hint = null;
public static function get _instance():Hint {
if (!__instance) {
__instance = new Hint();
}
return __instance;
}
And drop constructor, because getter makes it unnecessary.
Might be a silly question, but are you actually creating instance of Hint somewhere?
Because as long as you don't do new Hint() that Hint._instance will be null.
Try something like:
public class Hint extends Sprite
{
private static var _instance:Hint;
public function Hint()
{
if (_instance) throw new Error("Hint... use getInstance()");
_instance = this;
}
public static function getInstance():Hint
{
if (!_instance) new Hint();
return _instance;
}
//DrawHintText >> rename to drawHintText
public function drawHintText():void
{
//your code here
}
}
And to use:
Hint.getInstance().drawHintText();
Use Flash Builder, which costs some money, or Flash Develop. which is free. Both will show you compile time errors, with line numbers and location file.
Also at runtime will show you line number and the .as file where you have the problem.
Also autocomplete cuts your coding time by at least half time.
This is my level selector for a game. You can choose level 1-8, I need to know which one was clicked. e.target doesn't give me much besides the name of the object. I need to know either the place in the array or the name of the picture so I know which level to load up.
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class LevelSelector extends Sprite
{
private var posX:int = 50;
private var posY:int = 50;
[Embed(source="../lib/one.png")]
private var lvl1Class:Class;
private var lvl1:Bitmap = new lvl1Class();
[Embed(source="../lib/two.png")]
private var lvl2Class:Class;
private var lvl2:Bitmap = new lvl2Class();
[Embed(source="../lib/three.png")]
private var lvl3Class:Class;
private var lvl3:Bitmap = new lvl3Class();
[Embed(source="../lib/four.png")]
private var lvl4Class:Class;
private var lvl4:Bitmap = new lvl4Class();
[Embed(source="../lib/five.png")]
private var lvl5Class:Class;
private var lvl5:Bitmap = new lvl5Class();
[Embed(source="../lib/six.png")]
private var lvl6Class:Class;
private var lvl6:Bitmap = new lvl6Class();
[Embed(source="../lib/seven.png")]
private var lvl7Class:Class;
private var lvl7:Bitmap = new lvl7Class();
[Embed(source="../lib/eight.png")]
private var lvl8Class:Class;
private var lvl8:Bitmap = new lvl8Class();
private var myArrayBitmaps:Array = new Array;
private var myArraySprites:Array = new Array;
private var yCounter:int = 1;
public function LevelSelector():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
myArrayBitmaps.push(false, lvl1, lvl2, lvl3, lvl4, lvl5, lvl6, lvl7, lvl8);
for (var i:int = 1; i < 9; i++)
{
myArrayBitmaps[i].x = posX;
myArrayBitmaps[i].y = posY;
myArrayBitmaps[i].height = 50;
myArrayBitmaps[i].width = 100;
//myArrayBitmaps[i].name = "lvl_" + i + "";
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
myArraySprites[i].x = posX;
myArraySprites[i].y = posY;
//myArraySprites[i].name = "lvl_" + i + "";
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
removeThis(e, this);
});
posX += 100;
yCounter += 1;
if (yCounter == 5) {
posY += 100;
posX -= 400;
}
}
}
private function removeThis(e:MouseEvent, temp):void
{
//Need to know the number which was passed, 1-8
}
}
}
I would do something like this:
//...
private function init(e:Event = null):void
{
//...
for (var i:int = 1; i < 9; i++)
{
//...
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
//...
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, removeThis);
}
}
}
private function removeThis(e:MouseEvent):void
{
var clickTarget:int = myArraySprites.indexOf(e.currentTarget);
trace("Clicked sprite (id): " + clickTarget);
}