Post new topic This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Can anyone tell me how I can improve this code?
PostPosted: April 2nd, 2010, 9:41 am 
Steel Member
User avatar
Offline

Joined: January 19th, 2010, 5:45 am
Posts: 43 us
RS Name: Des_Zac
RS Status: P2P
Clan Name: Sara Flrs
This is my code I got from a tutorial site and I wanted to add a thing where when your hull (health is called hull for some reason) goes to 0 it goes to frame 2, but only when this happens. I also want it to have a button for you to restart.

Please help.

Thanks, Des_Zac

_________________
Finally back in to it, hopefully for good now!

THE ORIGINAL DES


Top
 Profile  
 
 Post subject: Register and login to get these in-post ads to disappear
PostPosted: April 2nd, 2010, 9:41 am 
Steel Member

Joined: September 9th, 2004, 1:47am
Posts: 9047
Location: In your web browserz


Top
  
 
 Post subject: Re: Can anyone tell me how I can improve this code?
PostPosted: April 5th, 2010, 2:30 pm 
Dragon Member
Offline

Joined: November 8th, 2006, 2:08 pm
Posts: 1931
Location: Florida us
RS Name: lKiwi
RS Status: Classic
May help if you posted the code.


Top
 Profile  
 
 Post subject: Re: Can anyone tell me how I can improve this code?
PostPosted: April 11th, 2010, 3:44 pm 
Steel Member
User avatar
Offline

Joined: January 19th, 2010, 5:45 am
Posts: 43 us
RS Name: Des_Zac
RS Status: P2P
Clan Name: Sara Flrs
here is the code (sorry forgot to add it :P)
P.S. I know how to make a restart button now, really simple XD

// Hero movement variables needed for the simulation
var centerHeroAngle:Number = degreesToRadians(270); // This is the absolute vertical position of the hero
var heroAngle:Number = centerHeroAngle; // This is the angle of the hero
var heroXPosition:Number = hero._x; // This is the current hero x position
var heroYPosition:Number = hero._y; // This is the current hero y position

// Bullet variables needed for the simulation
var bullets:Array = new Array();
var timeAtNextShot:Number = getTimer();
var bulletCounter:Number = 0;
var bulletHits:Number = 0;
var bulletMisses:Number = 0;

// Enemy variables needed for the simulation
var enemies:Array = new Array();
var enemyCounter:Number = 0; // How many enemies have we created
var deadEnemyCounter:Number = 0; // How many enemies have been killed
var escapedEnemyCounter:Number = 0; // How many enemies escaped
var timeAtNextEnemy:Number = getTimer() + 3000; // When will the next enemy be created

// Clip management
var parent:MovieClip = _root;
var workingDepth:Number = 1000;

// General variables
var lives:Number = 3;
var paused:Boolean = false;

// Contants needed for the simulation

// Hero
var heroXSpeed:Number = 6; // speed in pixels per frame along the x axis
var heroRotationSpeed:Number = degreesToRadians(2); // Max speed in degrees that the hero can move per frame
var heroMinAngle:Number = degreesToRadians(250); // Farthest left the hero can rotate
var heroMaxAngle:Number = degreesToRadians(290); // Farthest right the hero can rotate
var heroSmallTurnThreshold:Number = degreesToRadians(10); // Farthest right the hero can rotate


// Hero Energy
var maxEnergy:Number = 100; // Maximum energy the hero can have
var energy:Number = maxEnergy; // The current hero energy
var minEnergy:Number = 0; // The minimum energy the hero can have
var energyPerShot:Number = 2; // The amount of energy per shot
var energyRegenRate:Number = .006; // The energy regen rate increase per turn
var currentEnergyRegenRate:Number = energyRegenRate; // The current energy regen rate
var originalEnergyBarYPosition:Number = energyBar._y;

// Hero Shield
var maxShield:Number = 100;
var minShield:Number = 0;
var shield:Number = maxShield;
var shieldDamagePerHit:Number = 40;
var shieldRegenRate:Number = 0.1;
var originalShieldBarYPosition:Number = shieldBar._y;

// Hero Hull
var maxHull:Number = 100;
var minHull:Number = 0;
var hull:Number = maxHull;
var hullDamagePerHit:Number = 40;
var originalHullBarYPosition:Number = hullBar._y;

// Stage
var stageWidth:Number = 640; // The width of the stage in pixels
var stageHeight:Number = 480; // The height of the stage in pixels
var mouseYEndPosition:Number = 350; // The position at which the hero stops rotating towards the mouse

// Shooting
var minDelayBetweenShots:Number = 100; // the delay between shots in milliseconds
var bulletSpeed:Number = 16; // How fast the bullets move initially, this is arbitrary

// Enemies
var minTimeBetweenEnemies:Number = 500; // The minimum time between enemies
var maxTimeBetweenEnemies:Number = 2000; // The maximum time between enemies
var minEnemyFallRate:Number = 1; // The minimum speed enemies fall
var maxEnemyFallRate:Number = 5; // The maximum speed enemies fall
var enemyXOffset:Number = 30; // this is to prevent enemies from appearing only part way on the screen
var enemyBarrelLength:Number = 15;
var minTimeBetweenEnemyShots:Number = 1000; // The minimum time between enemy firings
var maxTimeBetweenEnemyShots:Number = 3000; // The maximum time between enemy firings

// Determine how close the bullet and ships need to be to collide
var enemyRadius:Number = 22;
var heroRadius:Number = 64;
var bulletRadius:Number = 3;
var enemyCollisionDistance:Number = (enemyRadius + bulletRadius) * (enemyRadius + bulletRadius);
var heroCollisionDistance:Number = (heroRadius + bulletRadius) * (heroRadius + bulletRadius);

// This is a hack to avoid using classes in the examples, see the "shoot" function
// for details
var X_POSITION:Number = 0;
var Y_POSITION:Number = 1;
var X_VELOCITY:Number = 2;
var Y_VELOCITY:Number = 3;
var ROTATION:Number = 4;
var OWNER:Number = 5;
var CLIP_HANDLE:Number = 6;

// Enemies
var TIME_AT_NEXT_SHOT = 7;

// Gun Settings
var X_OFFSET:Number = 0; // the x offset from the registration point of the hero
var Y_OFFSET:Number = 1; // the y offset from the registration point of the hero
var ANGLE_OFFSET:Number = 2; // the angle offset from the current angle of the hero

// These define each of the guns available on the ship
var guns:Array = new Array();
// This is the gun on the left side of the nose
guns[0] = new Array();
guns[0][X_OFFSET] = 3;
guns[0][Y_OFFSET] = 38;
guns[0][ANGLE_OFFSET] = degreesToRadians(0.4);

// This is the gun on the right side of the nose
guns[1] = new Array();
guns[1][X_OFFSET] = -3;
guns[1][Y_OFFSET] = 38;
guns[1][ANGLE_OFFSET] = degreesToRadians(-0.4);

// This is the gun on the left wing tip
guns[2] = new Array();
guns[2][X_OFFSET] = 42;
guns[2][Y_OFFSET] = -2;
guns[2][ANGLE_OFFSET] = degreesToRadians(5.5);

// This is the gun on the right wing tip
guns[3] = new Array();
guns[3][X_OFFSET] = -42;
guns[3][Y_OFFSET] = -2;
guns[3][ANGLE_OFFSET] = degreesToRadians(-5.5);

// Firing Modes
var SINGLE_FIRE:Number = 0;
var DUAL_FIRE:Number = 1;
var QUAD_FIRE:Number = 2;
var firingMode:Number = SINGLE_FIRE;

// Dual Fire Settings
var INNER_GUN_PAIR:Number = 0;
var OUTER_GUN_PAIR:Number = 1;
var currentFiringPair:Number = INNER_GUN_PAIR;

// Single Fire Settings
var currentGun:Number = 0;

// -=-=-=-=-=-=-=-=-
// Listener events
// -=-=-=-=-=-=-=-=-

// Register the mainLine
_root.onEnterFrame = mainLine;

// Create the mouse listener
var mouseListener:Object = new Object();

// Listen to movement
mouseListener.onMouseMove = function() {
trackMouseMovement();
}

// Listen to clicks
mouseListener.onMouseUp = function() {
trackMouseClick();
}

// Register the mouse listener
Mouse.addListener(mouseListener);

// Create the keyboard listener
var keyListener:Object = new Object();

// Listen to keys
keyListener.onKeyUp = function() {
var keyPressed:String = chr(Key.getAscii());
if(keyPressed == "p" || keyPressed == "P") {
togglePause();
} else if(keyPressed == "m" || keyPressed == "M") {
toggleFiringMode();
}
};

// Register the key listener
Key.addListener(keyListener);


// This function is invoked every time the mouse moves
function trackMouseMovement():Void {
// Update the heros angle in relation to the mouse
trackHeroPositionToMouse();
}

// This function is invoked every time the mouse button is clicked
function trackMouseClick():Void {
// Fire a shot
shoot();
}

// -=-=-=-=-=-=-=-=-
// Primary game functions
// -=-=-=-=-=-=-=-=-

// This is executed for each update of the simulation
function mainLine():Void {

// If we are paused, don't do anything
if(paused) {
return;
}

// Update simulation
updateSimulation();

// Renders everything
render();

}

// Updates the simulation in memory
function updateSimulation():Void {

// Updates the hero in memory
updateHero();

// Updates the bullets in memory
updateBullets();

// Updates the energy in memory
updateEnergy();

// Updates the shield in memory
updateShield();

// Updates the hull in memory
updateHull();

// Updates enemies in memory
updateEnemies();

// Checks collisions
checkCollisions();

}

// This is used to draw everything on the screen
function render():Void {

// Updates the hero on the screen
renderHero();

// Updates the bullets on the screen
renderBullets();

// Update the energy bar
renderEnergy();

// Updates the shield bar
renderShield();

// Updates the hull bar
renderHull();

// Render enemies
renderEnemies();

// Update the UI with the running values
updateUi();
}

// This is used to check the collisions between bullets and enemies
function checkCollisions():Void {

// Iterate over all the bullets checking for collision
// We do this in reverse so we can pull entries off the array without screwing up our positions
for(var i:Number = bullets.length - 1; i >= 0; i--) {

// Create some convenience variables
var bullet:Array = bullets[i];
var x1 = bullet[X_POSITION];
var y1 = bullet[Y_POSITION];

var collision:Boolean = false;

// Only check enemy collisions if it was fired by the hero
if(bullet[OWNER] == "hero") {

// Iterate over all the enemies
for(var j:Number = enemies.length -1; j >= 0; j--) {

// Create some convenience variables
var enemy:Array = enemies[j];
var x2:Number = enemy[X_POSITION];
var y2:Number = enemy[Y_POSITION];

// Get the distance
var distance = distanceBetween2DPoints(x1, y1, x2, y2, false);

// Are they colliding?
if(distance <= enemyCollisionDistance) {

// Flag that a collision occured so we can remove the bullet as well
collision = true;
deadEnemyCounter++;

// Remove the enemy
enemies.splice(j, 1);
enemy[CLIP_HANDLE].removeMovieClip();

// Leave our current loop, bullets are destroyed when they hit an enemy
break;
} // end colliding if statement
} // end enemies loop

// Check hero collisions
} else if(bullet[OWNER] == "enemy") {

// Get the distance
var distance = distanceBetween2DPoints(x1, y1, heroXPosition, heroYPosition, false);

// Are they colliding?
if(distance <= heroCollisionDistance) {

// Flag that a collision occured so we can remove the bullet
collision = true;

// Decrement the shield level
shield -= shieldDamagePerHit;

// If the shield has dropped below zero, we need to impact the hull
if(shield < minShield) {

// Decrease the difference from the hull
hull -= minShield - shield;

// If the hull is too low, your dead
if(hull < minHull) {
hull = minHull;
// DEAD :)
}

// Set the shield to the minimum
shield = minShield;
}

} // end colliding if statement

} // end enemy/hero check

// There was a collision, remove the bullet
if(collision) {
// Remove the bullet
bullets.splice(i, 1);
bullet[CLIP_HANDLE].removeMovieClip()
bulletHits++;
}


} // end bullets loop
}


// This is used to update any UI fields on the screen
function updateUi():Void {
scoreText.text = deadEnemyCounter * 10;
livesText.text = lives;
}

// Handle changing the firing mode
function toggleFiringMode():Void {
if(firingMode == SINGLE_FIRE) {
firingMode = DUAL_FIRE;
} else if(firingMode == DUAL_FIRE) {
firingMode = QUAD_FIRE;
} else if(firingMode == QUAD_FIRE) {
firingMode = SINGLE_FIRE;
}
}

// Handle pausing or unpausing the game
function togglePause():Void {
if(paused) {
resumeGame();
} else {
pauseGame();
}
}

// Pause the game
function pauseGame():Void {

// Pause the main loop
// Another technique would be to unregister the main loop function from the onEnterFrame
paused = true;

// Slap the pause menu onto the screen
var pauseMenu:MovieClip = parent.attachMovie("PauseMenu", "PauseMenu", workingDepth++);
pauseMenu._x = 0;
pauseMenu._y = 0;
pauseMenu._alpha = 50;
}

// Resume the game
function resumeGame():Void {

// Resume the main loop
paused = false;

// Remove the pause menu
parent["PauseMenu"].removeMovieClip();
}





// -=-=-=-=-=-=-=-=-
// Energy, Shield, and Hull Functions
// -=-=-=-=-=-=-=-=-

function updateEnergy():Void {
if(energy < maxEnergy) {
energy += currentEnergyRegenRate;
}

currentEnergyRegenRate += energyRegenRate;

if(energy > maxEnergy) {
energy = maxEnergy;
}
}

// Renders the energy bar
function renderEnergy():Void {
var height:Number = energy * 3; // This is lazy, it ought to be a min/max and be a ratio
energyBar._y = originalEnergyBarYPosition - height;
energyBar._height = height;
}

// Updates the shield status in memory
function updateShield():Void {
if(shield < maxShield) {
shield += shieldRegenRate;
}

if(shield > shield) {
shield = maxShield;
}
}

// Renders the shield bar
function renderShield():Void {
var height:Number = shield * 3; // This is lazy, it ought to be a min/max and be a ratio
shieldBar._y = originalShieldBarYPosition - height;
shieldBar._height = height;

// Adjust the alpha of the shield to match the alpha of the
hero.shield._alpha = shield;
}

// Updates the hull status in memory
function updateHull():Void {
// Do nothing at this point
}

// Renders the hull bar
function renderHull():Void {
var height:Number = hull * 3; // This is lazy, it ought to be a min/max and be a ratio
hullBar._y = originalHullBarYPosition - height;
hullBar._height = height;
}

// -=-=-=-=-=-=-=-=-
// Hero functions
// -=-=-=-=-=-=-=-=-

// This function tracks calculates the heros angle in relation to the mouse
function trackHeroPositionToMouse():Void {

// Pull the needed values
var x1:Number = _xmouse;
var y1:Number = _ymouse;
var x2:Number = hero._x;
var y2:Number = hero._y;

// Clamp the vertical mouse position to the maximum Y point
// This keeps the ship from swiveling around to face the wrong way, etc.
// Also lets you click the menu options that will be at the bottom of the screen
if(y1 > mouseYEndPosition) {
y1 = mouseYEndPosition;
}

// Determine the angle in radians between the mouse and hero
var angle:Number = determineAngleBetweenPoints(x1, x2, y1, y2);

// Rotate the angle to ensure we have the correct starting position
if(angle < 0) {
angle += 2 * Math.PI;
}

// Determine the new angle for the ship, taking into account rotation speed
var newAngle:Number = 0;
if(angle > heroAngle) {
newAngle = heroAngle + heroRotationSpeed;
if(newAngle > angle) {
newAngle = angle;
}
} else {
newAngle = heroAngle - heroRotationSpeed;
if(newAngle < angle) {
newAngle = angle;
}
}

// Clamp the rotation to the min and max angle
if(newAngle >= heroMaxAngle) {
newAngle = heroMaxAngle;
} else if(newAngle <= heroMinAngle) {
newAngle = heroMinAngle;
}

// Update the angle
heroAngle = newAngle;

// Update the stop position of the hero
heroStopXPosition = x1;

}

// This function creates a bullet and starts it moving
function shoot():Void {

// We can't shoot too fast, this prevents that
var currentTime:Number = getTimer();
if(currentTime > timeAtNextShot) {

// Determine what mode we are in and chose our guns
var gunsToShoot:Array = null;

// Fire all the guns at once
if(firingMode == QUAD_FIRE) {
gunsToShoot = new Array(4);
gunsToShoot[0] = guns[0];
gunsToShoot[1] = guns[1];
gunsToShoot[2] = guns[2];
gunsToShoot[3] = guns[3];

// Fire either the inside or outside pair of guns
} else if(firingMode == DUAL_FIRE) {
gunsToShoot = new Array(2);
if(currentFiringPair == INNER_GUN_PAIR) {
currentFiringPair = OUTER_GUN_PAIR;
gunsToShoot[0] = guns[0];
gunsToShoot[1] = guns[1];
} else {
currentFiringPair = INNER_GUN_PAIR;
gunsToShoot[0] = guns[2];
gunsToShoot[1] = guns[3];
}

// Fire a single gun, alternating which it is
} else if(firingMode == SINGLE_FIRE) {
gunsToShoot = new Array(1);
gunsToShoot[0] = guns[currentGun];
currentGun++;
if(currentGun > 3) {
currentGun = 0;
}
}

// Convenience variable to track the number of guns firing
var gunsFiring:Number = gunsToShoot.length;

// Do we have enough energy to shoot? If not, lets fail
if(energy <= energyPerShot * gunsFiring) {
return;
}

// Update the time we can shoot again based on the cooldown
timeAtNextShot = currentTime + (minDelayBetweenShots * gunsFiring);

// Update the number of bullets fired
bulletCounter++

// Reset the energy regen back to initial cause we shot
currentEnergyRegenRate = energyRegenRate;

// Decrement the amount of energy available by the number of guns fired
energy -= energyPerShot * gunsFiring;

// Loop over all the guns to fire this shot
for(var i:Number = 0; i < gunsFiring; i++) {

// Grab the current gun
var currentGun:Array = gunsToShoot[i];

// This is terrible, it needs to be a class but I'm using an
// array to keep things simple. Each position in the array
// contains a property of the bullet.
var bullet:Array = new Array();

// Set the starting position
bullet[X_POSITION] = heroXPosition + (currentGun[X_OFFSET] * Math.cos(heroAngle - Math.PI/2)) + (currentGun[Y_OFFSET] * Math.cos(heroAngle));
bullet[Y_POSITION] = heroYPosition + (currentGun[X_OFFSET] * Math.sin(heroAngle - Math.PI/2)) + (currentGun[Y_OFFSET] * Math.sin(heroAngle));

// Initalize the bullet x and y velocity using the heros angle
var newAngle:Number = heroAngle + currentGun[ANGLE_OFFSET];
bullet[X_VELOCITY] = bulletSpeed * Math.cos(newAngle);
bullet[Y_VELOCITY] = bulletSpeed * Math.sin(newAngle)

// Set the bullet's rotation
bullet[ROTATION] = newAngle;

// Indicate that the hero owns this bullet (so he can't shoot himself)
bullet[OWNER] = "hero";

// This will contain the movie clip representing the bullet
bullet[CLIP_HANDLE] = null;

// Add this bullet to the list of bullets
bullets.push(bullet);
}
}
}

// Updates the hero position in memory
function updateHero():Void {

// If we are too close, just snap to the position
// This prevents "jitter" of the hero trying to reach the mouse position and overshooting
var distanceFromStop:Number = Math.abs(heroStopXPosition - heroXPosition);
if(distanceFromStop <= heroXSpeed) {

heroXPosition = heroStopXPosition;

// Slide the hero in the right direction
} else {

// Determine how far we are to move and in what direction
var heroXUpdate:Number = heroXSpeed;
if(heroStopXPosition < heroXPosition) {
heroXUpdate *= -1;
}

// Update the heroXPosition variable
heroXPosition += Math.round(heroXUpdate);

}

// Force an update of the hero end position + angle again
// This is necessary because the hero needs to follow the mouse even
// if the mouse itself isnt moving
trackHeroPositionToMouse();

}

// This function actually renders the hero
function renderHero():Void {

// Update the X position of the hero as needed
var heroOldPosition:Number = hero._x;
hero._x = heroXPosition;

// If we are going left, right or center, update the hero clip
// NOTE: While this is implemented, there are no graphics for this. You just need
// to drop them into the hero clip to see it work.
// This takes into a close turn and a far turn
var directionFrame:String = "Straight";
var angularDistance:Number = Math.abs(centerHeroAngle - heroAngle);
if(heroOldPosition < heroXPosition) {
if(heroSmallTurnThreshold >= angularDistance) {
directionFrame = "Right";
} else {
directionFrame = "FarRight";
}
} else if(heroOldPosition > heroXPosition) {
if(heroSmallTurnThreshold >= angularDistance) {
directionFrame = "Left";
} else {
directionFrame = "FarLeft";
}
}
hero.gotoAndPlay(directionFrame);

// Rotate the hero as needed
hero._rotation = radiansToDegrees(heroAngle);
}




// -=-=-=-=-=-=-=-=-
// Bullet functions
// -=-=-=-=-=-=-=-=-

function updateBullets():Void {

// Iterate over all the bullets, updating their position
for(var i:Number = 0; i < bullets.length; i++) {

// Get a local reference to the bullet
var bullet:Array = bullets[i];

// Update the position of the bullet
bullet[X_POSITION] = bullet[X_POSITION] + bullet[X_VELOCITY];
bullet[Y_POSITION] = bullet[Y_POSITION] + bullet[Y_VELOCITY];

}
}

function renderBullets():Void {

// Iterate over all the bullets, updating their position
// We do this in reverse so we can pull entries off the array without screwing up our "i" position
for(var i:Number = bullets.length - 1; i >= 0; i--) {

// Get a local reference to the bullet and needed values
var bullet:Array = bullets[i];
var xPos:Number = bullet[X_POSITION];
var yPos:Number = bullet[Y_POSITION];
var clip:MovieClip = bullet[CLIP_HANDLE];

// If the clip is null, we haven't rendered it to the screen yet
if(clip == null) {
clip = parent.attachMovie("Bullet", "bullet" + bulletCounter, workingDepth++);
bullet[CLIP_HANDLE] = clip;

// Rotate the bullet as needed
clip._rotation = radiansToDegrees(bullet[ROTATION]);
}

// If we have exceeded the x/y dimentions of the game, remove the
// bullet from the array and the clip from the screen
if(xPos < 0 || xPos > stageWidth || yPos < 0 || yPos > stageHeight) {
bulletMisses++;
bullets.splice(i, 1);
clip.removeMovieClip()
continue;
}

// Update the clips position on the screen
clip._x = Math.round(xPos);
clip._y = Math.round(yPos);

}

}




// -=-=-=-=-=-=-=-=-
// Enemy functions
// -=-=-=-=-=-=-=-=-

// Updates the positions of the enemies in memory
function updateEnemies():Void {

// If enough time has passed, create a new enemy
if(getTimer() >= timeAtNextEnemy) {

// Increment the number of enemies total
enemyCounter++;

// Update the time when the next enemy appears
timeAtNextEnemy = getTimer() + randomNumberInRange(minTimeBetweenEnemies, maxTimeBetweenEnemies);

// This is terrible, look at the shoot method comments to see why
var enemy:Array = new Array();

// Set the starting position
enemy[X_POSITION] = randomNumberInRange(0, stageWidth - (enemyXOffset * 2)) + enemyXOffset;
enemy[Y_POSITION] = -30; // start a little off the screen

// Initalize the enemy x and y velocity
enemy[X_VELOCITY] = 0;
enemy[Y_VELOCITY] = randomNumberInRange(minEnemyFallRate, maxEnemyFallRate);

// When can this enemy fire it's next shot?
enemy[TIME_AT_NEXT_SHOT] = getTimer() + randomNumberInRange(minTimeBetweenEnemyShots, maxTimeBetweenEnemyShots);

// This will contain the movie clip representing the enemy
enemy[CLIP_HANDLE] = null;

// Add this enemy to the list of enemies
enemies.push(enemy);

}

// Iterate over all the enemies, updating their position
var currentTime = getTimer();
for(var i:Number = 0; i < enemies.length; i++) {

// Get a local reference to the enemy
var enemy:Array = enemies[i];

// Update the position of the enemy
enemy[X_POSITION] = enemy[X_POSITION] + enemy[X_VELOCITY];
enemy[Y_POSITION] = enemy[Y_POSITION] + enemy[Y_VELOCITY];

// Are we to shoot right now?
if(enemy[TIME_AT_NEXT_SHOT] < currentTime) {

// Create the bullet
var bullet:Array = new Array();

// Set the starting position
bullet[X_POSITION] = enemy[X_POSITION];
bullet[Y_POSITION] = enemy[Y_POSITION] + enemyBarrelLength;

// Initalize the bullet x and y velocity
bullet[X_VELOCITY] = 0;
bullet[Y_VELOCITY] = bulletSpeed;

// Set the bullet's rotation
bullet[ROTATION] = degreesToRadians(90);

// This will contain the movie clip representing the bullet
bullet[CLIP_HANDLE] = null;

// Flag an enemy as the owner of this bullet. This ensures we don't shoot ourselves
bullet[OWNER] = "enemy";

// Add this bullet to the list of bullets
bullets.push(bullet);

// Indicate when we will shoot again
enemy[TIME_AT_NEXT_SHOT] = getTimer() + randomNumberInRange(minTimeBetweenEnemyShots, maxTimeBetweenEnemyShots);
}

}
}

// Render the enemies on the screen
function renderEnemies():Void {

// Iterate over all the enemies, updating their position
// We do this in reverse so we can pull entries off the array without screwing up our "i" position
for(var i:Number = enemies.length - 1; i >= 0; i--) {

// Get a local reference to the bullet and needed values
var enemy:Array = enemies[i];
var xPos:Number = enemy[X_POSITION];
var yPos:Number = enemy[Y_POSITION];
var clip:MovieClip = enemy[CLIP_HANDLE];

// If the clip is null, we haven't rendered it to the screen yet
if(clip == null) {
clip = parent.attachMovie("Enemy", "enemy" + enemyCounter, workingDepth++);
enemy[CLIP_HANDLE] = clip;
}

// If we have exceeded the x/y dimentions of the game, remove the
// enemy from the array and the clip from the screen. Ignore the top
// of the screen as the enemies are always falling. We are checking left and right
// in case you want to make the enemies move on an angle
if(xPos < 0 || xPos > stageWidth || yPos > stageHeight) {
enemies.splice(i, 1);
clip.removeMovieClip()
escapedEnemyCounter++;
continue;
}

// Update the clips position on the screen
clip._x = Math.round(xPos);
clip._y = Math.round(yPos);

}

}




// -=-=-=-=-=-=-=-=-
// Utility functions
// -=-=-=-=-=-=-=-=-

// Gives the angle in radians between two points on a plane
function determineAngleBetweenPoints(x1:Number, x2:Number, y1:Number, y2:Number):Number {

// Find the distance
var xDistance:Number = x1 - x2;
var yDistance:Number = y1 - y2;

// Run the calculation
var angle:Number = Math.atan2(yDistance, xDistance);

// Return the results
return angle;
}

// Convert radians to degrees
function radiansToDegrees(radians:Number):Number {

// Perform the conversion equation
var degrees = radians * (180 / Math.PI);

// Return the results
return degrees;
}


// Convert degrees to radians
function degreesToRadians(degrees:Number):Number {

// Perform the conversion
var radians = degrees * (Math.PI / 180);

// Return the results
return radians;
}

// Returns a random whole number in between the range
function randomNumberInRange(min:Number, max:Number) {
var range = max - min;
var results:Number = Math.floor((Math.random() * range) + min);
return results;
}

// Calculates the distance between a pair of points
// To get a "correct" answer, set useSqrt to true but don't use that where performance matters
function distanceBetween2DPoints(x1:Number, y1:Number, x2:Number, y2:Number, useSqrt:Boolean):Number {
var xd:Number = x2 - x1;
var yd:Number = y2 - y1;
var distance:Number = (xd * xd) + (yd * yd);

if(useSqrt) {
distance = Math.sqrt(distance);
}

return distance;
}

// Stop the playhead
stop();

_________________
Finally back in to it, hopefully for good now!

THE ORIGINAL DES


Top
 Profile  
 
Display posts from previous:  Sort by  

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to: