XNA simple state machine doesn't do anything - xna

I'm working on a project for my Video Game Design class where I basically had to find some bugs in some code, fix it, and then convert it all into a state machine using an enumeration. I've pasted the initialize, update, and draw methods below, and as you can see, I've commented out the old code before converting it into a state machine. Everything was working fine before with all the if/else statements, but now that I've converted it, it doesn't actually do anything. It displays the standing sprite in the starting position, but pressing the keys does absolutely nothing.
INSTANTIATING VARIABLES
Texture2D heroineTexture, dive, duck, jump, stand;
int yVelocity, jumpVelocity, diveVelocity;
Rectangle player;
enum State
{
Standing,
Jumping,
Ducking,
Diving
};
State state;
KeyboardState kb, oldkb;
INITIALIZE
oldkb = Keyboard.GetState();
jumpVelocity = -10;
diveVelocity = 15;
yVelocity = 0;
heroineTexture = stand;
state = State.Standing;
player = new Rectangle(0, 430, 50, 40);
base.Initialize();
UPDATE
kb = Keyboard.GetState();
// Allows the game to exit
if (kb.IsKeyDown(Keys.Escape))
this.Exit();
// TODO: Add your update logic here
player.Y += yVelocity;
switch (state)
{
case State.Standing:
if (kb.IsKeyDown(Keys.J))
{
state = State.Jumping;
yVelocity = jumpVelocity;
heroineTexture = jump;
}
else if (kb.IsKeyDown(Keys.Down))
{
state = State.Ducking;
heroineTexture = duck;
}
break;
case State.Jumping:
if (kb.IsKeyDown(Keys.Down))
{
state = State.Diving;
heroineTexture = dive;
yVelocity = diveVelocity;
}
break;
case State.Ducking:
if (!kb.IsKeyDown(Keys.Down))
{
state = State.Standing;
heroineTexture = stand;
}
break;
}
if (player.Y >= 430)
{
state = State.Standing;
player.Y = 430;
yVelocity = 0;
heroineTexture = stand;
}
//if (kb.IsKeyDown(Keys.J) && oldkb.IsKeyUp(Keys.J))
//{
// if (!isJumping && !isDucking)
// {
// isJumping = true;
// yVelocity = jumpVelocity;
// heroineTexture = jump;
// }
//}
//else if(kb.IsKeyDown(Keys.Down))
//{
// if(!isJumping)
// {
// if(isDiving)
// {
// yVelocity = diveVelocity;
// }
// else if(!isJumping && !isDiving)
// {
// isDucking = true;
// heroineTexture = duck;
// }
// }
// else
// {
// isJumping = false;
// heroineTexture = dive;
// isDiving = true;
// }
//}
//else if(!kb.IsKeyDown(Keys.Down))
//{
// if(isDucking)
// {
// isDucking = false;
// heroineTexture = stand;
// }
//}
oldkb = kb;
base.Update(gameTime);

generally: set a breakpoint on every line where you SET the state, start debugging and you'll find the culprit.
Anyway. In your commented code, you did the player.y >= 430 check BEFORE handling the states, but now you do it afterwards.
You are basically setting the state but not changing the position, so, if I guess correct, your player was standing (>= 430), you set the state and immediatly afterwards (before actually changing the player.y) the player is still standing and you setting the state back to standing.
This is just guessing from your code snippet because the location of the "if player.y >= 430" actually is called at a different time now
you need to do this:
player.Y += yVelocity;
AFERT the switch/case but BEFORE the
if(player.y >= 430)

Related

SpriteWidget: App doesn't response to handleEvent in NodeWithSize

I created a widget, added some Sprites and made some animation. I want to add some user interaction but handelEvent method is not working. I already set userInteractionEnabled to true.
I tried debugging and place a breakpoint inside the handleEvent method but it didn't stop when I touched the screen.
class MainSceneBackgroundNode extends NodeWithSize {
Sprite _logo;
RepeatedImage _background;
GuyImage _guy;
int _i = 0;
int _j = 0;
int _dir = -1;
MainSceneBackgroundNode() : super(new Size(2560.0, 1440.0)) {
userInteractionEnabled = true;
handleMultiplePointers = false;
// Add background
_background = new RepeatedImage(_imageMap["assets/background.png"]);
addChild(_background);
_guy = new GuyImage();
addChild(_guy);
_logo = new Sprite.fromImage(_imageMap["assets/logo.gif"]);
_logo.pivot = Offset.zero;
_logo.size = new Size(912, 486);
_logo.position = new Offset(824, 10);
addChild(_logo);
}
#override
bool handleEvent(SpriteBoxEvent event) {
if (event.type == PointerDownEvent) {
if (event.boxPosition.dx < 1280) {
_dir = -1;
} else {
_dir = 1;
}
}
return true;
}
...
}
Any suggestion will be appreciated. I don't know what else to do.
Thanks in Advance.

Need code to make animation to stop

Trying to stop this animation on frame 109 in as2. Any help in what I need to ad to get this to stop. It is a confetti animation.
cnfNumber = 85;
var cnfs:Array = new Array("cnf", "cnf2", "cnf3","cnf4","cnf5")
for (i=0; i<cnfNumber; i++) {
newCnf = _root[cnfs[random(cnfs.length)]].duplicateMovieClip("snow"+i, i);
newCnf._x = Math.random()*Stage.width;
newCnf._y = -Math.random()*300;
newCnf.maxCnfSpeed = Math.random()*4;
newCnf.wind = Math.random()*6;
newCnf._xscale = newCnf._yscale = newCnf.alpha = Math.random()*65+35
newCnf.onEnterFrame = function() {
this._rotation -= this.maxCnfSpeed+1;
if(this._y>Stage.height || this._x>Stage.width || this._x<0){
this._y = -Math.random()*300;
this._x = Math.random()*Stage.width;
} else {
this._y += this.maxCnfSpeed+2;
this._x += this.wind-4;
}
this._alpha = this.alpha;
};
}
Why not just do this:
newCnf._xscale = newCnf._yscale = newCnf.alpha = Math.random()*65+35
newCnf.frameCount = 0;
newCnf.onEnterFrame = function() {
if(this.frameCount<109) {
this._rotation -= this.maxCnfSpeed+1;
if(this._y>Stage.height || this._x>Stage.width || this._x<0){
this._y = -Math.random()*300;
this._x = Math.random()*Stage.width;
} else {
this._y += this.maxCnfSpeed+2;
this._x += this.wind-4;
}
this._alpha = this.alpha;
this.frameCount++;
} else {
this.onEnterFrame = null;
}
};
I haven't worked in Actionscript in a while, so the this.onEnterFrame = null may not be quite correct, but it's not strictly necessary; it just keeps the confetti from checking the frame number and bailing out every frame once it's done animating.
If you want the confetti to disappear rather than freezing in place, unload it instead of clearing its onEnterFrame. I don't remember the function that does that off the top of my head, but the documentation for duplicateMovieClip should have a link to it.
(I won't ask why you're still using AS2.)

How can I hit test between two arrays whilst switching between movieclips within those arrays?

I am making a platforming game in which I must switch between colliding the character between two Arrays (whiteBlocks and blackBlocks) as well as another Array (redBlocks) that is activated on button collision and is timed.
However, I am having trouble with the hitTest code I have used to ensure that I can use redBlocks as a platform as well as either whiteBlocks or blackBlocks at the same time. I was wandering if anyone could help me to have the redBlocks constantly active once the timer has been triggered and is not effective by switching between blackBlocks or whiteBlocks.
If you would like me to explain my problem in a clearer way I will do. Please note that I am quite new to actionscript and coding in general so apologies for errors I may make. I appreciate any help you can offer as I have been troubleshooting this for a while now.
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.events.Event;
import flash.display.MovieClip
import flash.display.DisplayObject;
//PLAYER MOVEMENT
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyLIST);
stage.addEventListener(KeyboardEvent.KEY_UP, keyLIST);
manMC.positionPNT = new Point (manMC.x, manMC.y);
//track using loop and keypresses, not just keyEvent
var leftKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
function keyLIST (ke:KeyboardEvent) {
//trace(ke.toString() );
//1. work out where we're going from where we are now
//characterPNT = new Point(manMC.x, manMC.y);
//2. offset our destination point
switch (ke.keyCode) {
//LEFT
case 37:
trace(ke.type);
leftKeyDown = (ke.type == "keyDown");
break;
//RIGHT
case 39:
//moveCharacter(manMC, "right");
rightKeyDown = (ke.type == "keyDown");
break;
//87UP, 83DOWN
//UP
case 38:
trace("true");
manMC.jump();
break;
//DOWN
case 83:
break;
default:
//trace ("this key does nothing");
break;
}// close switch
}// end function keyLIST
function movementCallback (ev:Event):void {
if (leftKeyDown == true) {
moveCharacter(manMC, "left");
}
if (rightKeyDown == true) {
moveCharacter(manMC, "right");
}
}
addEventListener (Event.ENTER_FRAME, movementCallback);
//a new movement function
function moveCharacter(char:character, dir:String ):void {//datatype as void as it returns nothing
//will need this
//var characterPNT:Point; //moved to character class
//maMC.positionPNT = new Point( manMC.x, manMC.y);
//copy current poistion before offsetting with movement, speed and direction
manMC.destinationPNT = manMC.positionPNT.clone();
//characterPNT = new Point(manMC.x, manMC.y);
//var colliding:Boolean;
//do multiple collision detection here
var offsetPNT:Point;//detecting the destination of the body points
switch (dir) {
case "left":
//move PNT to left
manMC.destinationPNT.x -= manMC.speedNUM;
offsetPNT = manMC.leftarmPNT;
break;
case "right":
//move PNT to right
manMC.destinationPNT.x += manMC.speedNUM;
offsetPNT = manMC.rightarmPNT;
break;
}
//set to true of false by the function that returns a Boolean value
var colliding:Boolean = multipleHitTest (manMC.positionPNT, manMC.destinationPNT, offsetPNT, activeArray);
//trace(colliding);
//trace ("moveMode: " + manMC.moveModeSTR);
if (!colliding /*&& manMC.moveModeSTR != "falling"*/) { //may be more complex to control player movement when falling&jumping
manMC.moveToPoint( manMC.destinationPNT );
//manMC.x = manMC.destinationPNT.x;
//manMC.y = manMC.destinationPNT.y;
//always update position PNT when character is moved
//manMC.positionPNT = manMC.destinationPNT.clone();//copies destination point
}
}
//Apply gravity at all times using a loop/callback
addEventListener(Event.ENTER_FRAME, gravityFUNC);
var gravityNUM:Number = new Number(10);
function gravityFUNC (ev:Event) {
var falling:Boolean;
var gravityPNT:Point = manMC.positionPNT.clone();
//trace(manMC.positionPNT.y);
gravityPNT.y += gravityNUM;
//trace(gravityPNT.y);
//EXPERIMENTAL
gravityPNT.y -= manMC.verticalVelocityNUM;
//decaying gravity, caping it at 0 to avoid negatives
manMC.verticalVelocityNUM = Math.max ( 0, manMC.verticalVelocityNUM - gravityNUM);
falling = !multipleHitTest (manMC.positionPNT, gravityPNT, manMC.feetPNT, activeArray);
//trace("falling " + falling);
if (falling == true) {
//manMC.y = gravityPNT.y;
manMC.moveToPoint(gravityPNT);
//either jumping or falling
if ( manMC.verticalVelocityNUM == 0) {
manMC.moveModeSTR = "falling";
}else {
manMC.moveModeSTR = "jumping";
}
} else {
manMC.moveModeSTR = "walking";
}
}
//======================================================================
//======================================================================
//add when declared
//varobstacles:Array = new Array (block0MC, block1MC, block2MC);
//declared and then new instance
//var obstacles:Array;
//obstacles = new Array (block6MC);
//declares and create empty array
/*var obstacles:Array = new Array();
//push adds an item to the front of an array
obstacles.push (block0MC); // add instance names of display objects (or other data)
obstacles.push (block1MC);
obstacles.push (block2MC);
obstacles.push (block3MC);*/
//trace("length of list" + obstacles.length);
//trace(obstacles[0]); //access first element of array
//trace( block0MC["x"] );// acessing x property using different method
function multipleHitTest( position:Point, destination:Point, offset:Point, targets:Array):Boolean { //these are ARGUMENTS
//track hittest true or false
var returnBOOL:Boolean = new Boolean (false);
// cap length of loop - ie.e how many iterations?
var limit:int = new int ( targets.length );// obstacles.length is 3 items long
//the "counter", increases or decreases each time
var i:int;
//chunks =
//start counter at 0;
// loop while counter is less than limit;
// increment counter by 1 each looop;
for( i=0; i<limit; i++) {
//will access each item in array, as "i" is an integer
//obstacles[1];
//because it's targeted as a movieclip we can ask it's name
//this is 'reference variable'
//we are creating an 'alias' of the item in the list
var testAgainstObject:DisplayObject = targets[i];
//track direction
var moveDirection:String;
//only hit test things we're moving towards...
if (position.x < destination.x) { //if we're moving right
moveDirection = new String( "right" );
} else if (position.x > destination.x) {//else if we're moving left
moveDirection = new String( "left" );
}
//
if(
(moveDirection == "right" && targets[i].x >= position.x && destination.x >= targets[i].x)
||//or
(moveDirection == "left" && targets[i].x <= position.x && destination.x <= (targets[i].x + targets[i].width) )
) {//obstacle is to the right
// obstacle moving right
// moving right
}
//create a copy of 'destination'
var offsetDestination:Point = destination.clone();
//apply our offset provided by our character limbs
offsetDestination.offset(offset.x, offset.y);
//if point is colliding with list item
//if( testAgainstObject.hitTestPoint (destination.x, destination.y) ) { //REMOVED FOR TESTING
if( testAgainstObject.hitTestPoint (offsetDestination.x, offsetDestination.y) ) {
//trace("collisiondetected " + targets[i].name);
returnBOOL = true;
} else {
//trace("no collision");
//do nothing if flase, as it would contradict a 'true' value set earlier in the loop
}
}
return (returnBOOL); //tesing only
}
//declares and create empty array
var blackBlocks:Array = new Array();
//push adds an item to the front of an array
blackBlocks.push (block0MC); // add instance names of display objects (or other data)
blackBlocks.push (block1MC);
blackBlocks.push (blackbarrier);
blackBlocks.push (blackbarrier2);
blackBlocks.push (blackbarrier3);
blackBlocks.push (blackbarrier4);
blackBlocks.push (blackbarrier5);
var whiteBlocks:Array = new Array();
//push adds an item to the front of an array
whiteBlocks.push (block2MC);
whiteBlocks.push (block3MC);
whiteBlocks.push (whitebarrier);
whiteBlocks.push (whitebarrier2);
whiteBlocks.push (whitebarrier3);
whiteBlocks.push (whitebarrier4);
whiteBlocks.push (whitebarrier5);
var redBlocks:Array = new Array();
redBlocks.push (redblock1MC);
//var activeArray:Array = new Array (blackBlocks);
var activeArray:Array = blackBlocks;
//active.push (redblock1MC);
//Adds an event listener to the button component with the mouse click event.
//hide_btn.addEventListener(MouseEvent.CLICK, toggleBlocks);
//show_btn.addEventListener(MouseEvent.CLICK, showObject);
stage.addEventListener(KeyboardEvent.KEY_DOWN, toggleBlocks);
// start toggle blocks
function toggleBlocks (event:KeyboardEvent):void {
var i:int = 0;
var lim:int = activeArray.length;
if(event.keyCode == Keyboard.SPACE){
trace("Toggle Blocks");
blocksVisibility( activeArray , false );
if( activeArray == blackBlocks) {
activeArray = whiteBlocks;
}else{
activeArray = blackBlocks;
}
blocksVisibility( activeArray , true );
} // end IF
} // end toggle blocks
function blocksVisibility( arrARG:Array , visBOOL:Boolean ){
var i:int = 0;
var lim:int = arrARG.length;
for( i=0; i<lim; i++) {
arrARG[i].visible = visBOOL;
}
}
blocksVisibility( this.whiteBlocks , false );
blocksVisibility( this.redBlocks , false );
//blocksVisibility( this.redBlocks , false );
//======== red block button ========
// on collision trigger button and make red platform appear
/*
var myTimer:Timer = new Timer(5000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void {
//logo_mc.x+=40;
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
//activeArray:Array = redBlocks;
}
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onComplete);
function onComplete(e:TimerEvent):void {
//logo_mc.alpha=10;
//logo_mc.x=20;
blocksVisibility( this.redBlocks , false );
//redBlock1MC:Array = false;
//activeArray:Array = blackBlocks;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, onStart);
function onStart(e:KeyboardEvent):void {
if (e.keyCode == 88){
blocksVisibility( this.redBlocks , true );
//redBlock1MC:Array = true;
myTimer.start();
//logo_mc.alpha=.1;
//logo_mc.x=20;
}
} */
var myTimer:Timer = new Timer(10000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, timedPlatform);
//myTimer.start();
function timedPlatform(event:TimerEvent):void {
trace("timedPlatform() called # " + getTimer() + " ms");
blocksVisibility( this.redBlocks , false );
/*if (manMC.hitTestObject(redButton)){
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = redBlocks;
} */
}
redButton.addEventListener(Event.ENTER_FRAME, startTimer);
function startTimer(event:Event):void{
//if (e.keyCode == 88){
//if (manMC, hitTest(redButton)) {
if (manMC.hitTestObject(redButton)) {
trace("Start Timer");
myTimer.start();
blocksVisibility( this.redBlocks , true );
activeArray = blackBlocks;
//activeArray = blackBlocks;
/*if( activeArray == blackBlocks) {
activeArray = redBlocks;
activeArray = blackBlocks;
}else{
activeArray = blackBlocks;
}*/
}
}
Instead of making activeArray a reference to whiteBlocks or blackBlocks, make it a separate Array object. Then, in toggleBlocks, you can
remove all elements from activeArray
add all elements from redBlocks to activeArray (optional depending on the current state)
add all elements from whiteBlocks OR blackBlocks to activeArray
This way activeArray will have all red blocks AND (all whiteBlocks OR all blackBlocks).

Actionscript3 ArgumentError: Error #2109:

Making a touch based platform game based in actionscript 3 using Gary Rosenzweig's game as a basis, all was going well until today, I've been trying to swap out floor objects etc without changing much of the actionscript at all and I have the following error.
ArgumentError: Error #2109: Frame label jump not found in scene jump.
at flash.display::MovieClip/gotoAndStop()
at PlatformGame/moveCharacter()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:418]
at PlatformGame/moveEnemies()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:314]
at PlatformGame/gameLoop()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:303]
This also seems to cause problems with collision detection.
The code is as follows. (not i have not changed the scene or label names from the originals but it still shows the error).
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class PlatformGame extends MovieClip {
// movement constants
static const gravity:Number = .004;
// screen constants
static const edgeDistance:Number = 100;
public var rightButton:SimpleButton;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String = "start";
private var playerLives:int;
private var lastTime:Number = 0;
// start game
public function startPlatformGame() {
playerObjects = new Array();
gameScore = 0;
gameMode = "play";
playerLives = 3;
}
// start level
public function startGameLevel() {
// create characters
createHero();
addEnemies();
// examine level and note all objects
examineLevel();
// add listeners
this.addEventListener(Event.ENTER_FRAME,gameLoop);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchRight);
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_END,touchRightReleased);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchLeft);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_END,touchLeftReleased);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_BEGIN,jump);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_END,jumpReleased);
trace("hi"+gamelevel["rButton"]);
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHarder() {
// create characters
createHero();
addHardEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHardest() {
// create characters
createHero();
addHardestEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// creates the hero object and sets all properties
public function createHero() {
hero = new Object();
hero.mc = gamelevel.hero;
hero.dx = 0.0;
hero.dy = 0.0;
hero.inAir = false;
hero.direction = 0;
hero.animstate = "stand";
hero.walkAnimation = new Array(2,3,4,5,6,7,8);
hero.animstep = 0;
hero.jump = false;
hero.moveLeft = false;
hero.moveRight = false;
hero.jumpSpeed = .8;
hero.walkSpeed = .15;
hero.width = 15.0;
hero.height = 35.0;
hero.startx = hero.mc.x;
hero.starty = hero.mc.y;
}
// finds all enemies in the level and creates an object for each
public function addEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .15;
enemy.width = 56.0;
enemy.height = 80.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardestEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .25;
enemy.width = 40.0;
enemy.height = 40.0;
enemies.push(enemy);
i++;
}
}
// look at all level children and note walls, floors and items
public function examineLevel() {
fixedObjects = new Array();
otherObjects = new Array();
for(var i:int=0;i<this.gamelevel.numChildren;i++) {
var mc = this.gamelevel.getChildAt(i);
// add floors and walls to fixedObjects
if ((mc is Floor) || (mc is Wall) || (mc is ground1) || (mc is wall1) || (mc is ledge1) || (mc is ledge2) || (mc is rock) ||(mc is rocktip)) {
var floorObject:Object = new Object();
floorObject.mc = mc;
floorObject.leftside = mc.x;
floorObject.rightside = mc.x+mc.width;
floorObject.topside = mc.y;
floorObject.bottomside = mc.y+mc.height;
fixedObjects.push(floorObject);
// add treasure, key and door to otherOjects
} else if ((mc is Treasure) || (mc is Key) || (mc is Door) || (mc is Chest)) {
otherObjects.push(mc);
}
}
}
// note key presses, set hero properties
public function touchRight(event:TouchEvent) {
trace("touchRight");
hero.moveRight = true;
}
public function touchRightReleased(event:TouchEvent) {
hero.moveRight = false;
}
public function touchLeft(event:TouchEvent) {
hero.moveLeft = true;
}
public function touchLeftReleased(event:TouchEvent) {
hero.moveLeft = false;
}
public function jump(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = true;
}
}
public function jumpReleased(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = false;
}
}
// note key presses, set hero properties
//public function keyDownFunction(event:KeyboardEvent) {
//if (gameMode != "play") return; // don't move until in play mode
//if (event.keyCode == 37) {
//hero.moveLeft = true;
//} else if (event.keyCode == 39) {
//hero.moveRight = true;
//} else if (event.keyCode == 32) {
//if (!hero.inAir) {
//hero.jump = true;
//}
//}
//}
//public function keyUpFunction(event:KeyboardEvent) {
//if (event.keyCode == 37) {
//hero.moveLeft = false;
//} else if (event.keyCode == 39) {
//hero.moveRight = false;
//}
//}
// perform all game tasks
public function gameLoop(event:Event) {
// get time differentce
if (lastTime == 0) lastTime = getTimer();
var timeDiff:int = getTimer()-lastTime;
lastTime += timeDiff;
// only perform tasks if in play mode
if (gameMode == "play") {
moveCharacter(hero,timeDiff);
moveEnemies(timeDiff);
checkCollisions();
scrollWithHero();
}
}
// loop through all enemies and move them
public function moveEnemies(timeDiff:int) {
for(var i:int=0;i<enemies.length;i++) {
// move
moveCharacter(enemies[i],timeDiff);
// if hit a wall, turn around
if (enemies[i].hitWallRight) {
enemies[i].moveLeft = true;
enemies[i].moveRight = false;
} else if (enemies[i].hitWallLeft) {
enemies[i].moveLeft = false;
enemies[i].moveRight = true;
}
}
}
// primary function for character movement
public function moveCharacter(char:Object,timeDiff:Number) {
if (timeDiff < 1) return;
// assume character pulled down by gravity
var verticalChange:Number = char.dy*timeDiff + timeDiff*gravity;
if (verticalChange > 15.0) verticalChange = 15.0;
char.dy += timeDiff*gravity;
// react to changes from key presses
var horizontalChange = 0;
var newAnimState:String = "stand";
var newDirection:int = char.direction;
if (char.moveLeft) {
// walk left
horizontalChange = -char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = -1;
} else if (char.moveRight) {
// walk right
horizontalChange = char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = 1;
}
if (char.jump) {
// start jump
char.jump = false;
char.dy = -char.jumpSpeed;
verticalChange = -char.jumpSpeed;
newAnimState = "jump";
}
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for(var i:int=0;i<fixedObjects.length;i++) {
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside)) {
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside)) {
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
}
}
}
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for(i=0;i<fixedObjects.length;i++) {
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside)) {
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside)) {
newX = fixedObjects[i].rightside+char.width/2;
char.hitWallLeft = true;
break;
}
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside)) {
newX = fixedObjects[i].leftside-char.width/2;
char.hitWallRight = true;
break;
}
}
}
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir) {
newAnimState = "";
}
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk") {
char.animstep += timeDiff/60;
if (char.animstep > char.walkAnimation.length) {
char.animstep = 0;
}
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
} else {
char.mc.gotoAndStop(char.animstate);
}
// changed directions
if (newDirection != char.direction) {
char.direction = newDirection;
char.mc.scaleX = char.direction*1.35;
}
}
// scroll to the right or left if needed
public function scrollWithHero() {
var stagePosition:Number = gamelevel.x+hero.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge) {
gamelevel.x -= (stagePosition-rightEdge);
gamelevel["rButton"].x += (stagePosition-rightEdge);
gamelevel["lButton"].x += (stagePosition-rightEdge);
gamelevel["jButton"].x += (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth)) gamelevel.x = -(gamelevel.width-stage.stageWidth);
}
if (stagePosition < leftEdge) {
gamelevel.x += (leftEdge-stagePosition);
gamelevel["rButton"].x -= (leftEdge-stagePosition);
gamelevel["lButton"].x -= (leftEdge-stagePosition);
gamelevel["jButton"].x -= (leftEdge-stagePosition);
if (gamelevel.x > 0) gamelevel.x = 0;
}
}
// check collisions with enemies, items
public function checkCollisions() {
// enemies
for(var i:int=enemies.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(enemies[i].mc)) {
// is the hero jumping down onto the enemy?
if (hero.inAir && (hero.dy > 0)) {
enemyDie(i);
} else {
heroDie();
}
}
}
// items
for(i=otherObjects.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(otherObjects[i])) {
getObject(i);
}
}
}
// remove enemy
public function enemyDie(enemyNum:int) {
var pb:PointBurst = new PointBurst(gamelevel,"Got Em!",enemies[enemyNum].mc.x,enemies[enemyNum].mc.y-20);
gamelevel.removeChild(enemies[enemyNum].mc);
enemies.splice(enemyNum,1);
}
// enemy got player
public function heroDie() {
// show dialog box
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
if (playerLives == 0) {
gameMode = "gameover";
dialog.message.text = "Game Over!";
} else {
gameMode = "dead";
dialog.message.text = "He Got You!";
playerLives--;
}
hero.mc.gotoAndPlay("die");
}
// player collides with objects
public function getObject(objectNum:int) {
// award points for treasure
if (otherObjects[objectNum] is Treasure) {
var pb:PointBurst = new PointBurst(gamelevel,100,otherObjects[objectNum].x,otherObjects[objectNum].y);
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
addScore(100);
// got the key, add to inventory
} else if (otherObjects[objectNum] is Key) {
pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
// hit the door, end level if hero has the key
} else if (otherObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return;
if (otherObjects[objectNum].currentFrame == 1) {
otherObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
// got the chest, game won
} else if (otherObjects[objectNum] is Chest) {
otherObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
// add points to score
public function addScore(numPoints:int) {
gameScore += numPoints;
scoreDisplay.text = String(gameScore);
}
// update player lives
public function showLives() {
livesDisplay.text = String(playerLives);
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
// game over, bring up dialog
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
// dialog button clicked
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
showLives();
hero.mc.x = hero.startx;
hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
}
}
}
The error is with the following line and is occurring because the referenced MovieClip does not have a frame labelled "jump":
char.mc.gotoAndStop(char.animstate);
My guess is that you made a change to the MovieClip which contains your character and, in doing so, removed the label which the code above references.

Actionscript 2: Tween running extremely slow

I am using the following code to tween an movieclip once _global.choiceMade equals 1...
onClipEvent (load) {
import mx.transitions.Tween;
import mx.transitions.easing.*;
}
onClipEvent (enterFrame) {
if (_global.choiceMade == 1) {
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
}
}
This is contained within each frame of the main timeline. The first time it runs fine but on the next frame it runs incredibly slow (takes about 12 seconds not 0.5 and is very choppy), if I then return to the first frame and run it again now this time it is extremely slow.
I can't work out why its doing this my CPU stays around 6-15% while its running so it can't be too demanding.
Updated to show rest of my code:
On main timeline have a frame each containing a movieclip. On the timeline of each of these movieclips contains:
//tint an object with a color just like Effect panel
//r, g, b between 0 and 255; amount between 0 and 100
Color.prototype.setTint = function(r, g, b, amount) {
var percent = 100-amount;
var trans = new Object();
trans.ra = trans.ga=trans.ba=percent;
var ratio = amount/100;
trans.rb = r*ratio;
trans.gb = g*ratio;
trans.bb = b*ratio;
this.setTransform(trans);
};//Robert Penner June 2001 - http://www.robertpenner.com
MovieClip.prototype.scaleXY = function(to){
this.onEnterFrame = function(){
this._alpha = to-(to-this._alpha)/1.2;
if(this._alpha > to-1 && this._alpha < to+1){
this._alpha = to;
delete this.onEnterFrame
}
}
}
scoreUpdated = 0;
Answer = 1;
_global.choiceMade = 0;
Buttons = new Array(this.buttonHolder.True, this.buttonHolder.False);
Answers = new Array(this.Correct, this.Wrong);
for (i=0; i<Answers.length; i++) {
Answers[i]._alpha = 0;
}
for (b=0; b<Buttons.length; b++) {
Buttons[b].thisValue = b;
}
In this movieclip there are two movieclip buttons (True and False) containing this code:
onClipEvent (enterFrame) {
this.onRollOver = function() {
this.gotoAndStop("over");
};
this.onRollOut = function() {
this.gotoAndStop("up");
};
this.onPress = function() {
this.gotoAndStop("down");
};
this.onReleaseOutside = function() {
this.gotoAndStop("up");
};
this.onRelease = function() {
this.gotoAndStop("down");
whichChoice = this;
_global.choiceMade = 1;
counter = 0;
};
if (_global.choiceMade == 1) {
this.enabled = false;
this._parent.scoreNow = _global.score;
this._parent.scoreOutOf = (this._parent._parent._currentframe)- 1 + ( _global.choiceMade);
if (thisValue == this._parent._parent.Answer && whichChoice == this) {
myColor = new Color(this);
myColor.setTint(0,204,0,13);
this._parent._parent.Answers[0]._alpha = 100;
this._parent._parent.Answers[0].scaleXY(100);
this.tick.swapDepths(1000);
if (counter == 0) {
_global.score++;
counter++;
}
}
else if (thisValue == this._parent._parent.Answer) {
myColor = new Color(this);
myColor.setTint(0,204,0,13);
this.tick.swapDepths(1000);
}
else if (whichChoice == this) {
this._parent._parent.Answers[1]._alpha = 100;
this._parent._parent.Answers[1].scaleXY(100);
myColor = new Color(this);
myColor.setTint(255,0,0,13);
this.cross.swapDepths(1000);
}
else {
myColor = new Color(this);
myColor.setTint(255,0,0,13);
myColor.setTint(255,0,0,13);
this.cross.swapDepths(1000);
}
}
}
The script at the top is on a movieclip these buttons are contained in called buttonHolder which does what it says, and tweens the buttons across the screen to reveal a next button once an answer is chosen.
From what I can see, as long as you have choiceMade == 1 you create a new effect! which is not ok. because in 1 sec at 15 fps you will have 15 tweens running :(
try yo set choiceMade = 0 or somehting else than 1
onClipEvent (enterFrame)
{
if (_global.choiceMade == 1)
{
_global.choiceMade = -1;
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
}
}
Without seeing the rest of your code it's hard to see exactly what's going on. But it looks like you never change choiceMade and it continuously recreates the tween.
onClipEvent (enterFrame) {
if (_global.choiceMade == 1) {
var myTweenX:Tween = new Tween(this, "_x", mx.transitions.easing.Back.easeOut, this._x, -349, 0.5, True);
_global.choiceMade = 0;
}
}

Resources