Adding another Movie Clip into another Frame - actionscript-3

I am attempting to add a new movie clip into the next frame of my shooter game.
I am using Actionscript 3.0
To give a basis of what I need help with for my assessment. When the score =50, switch to the next frame. And this is where I would like to add a new type of movie clip for the user to shoot!
Here is the code I have so far.
FRAME 1
//Tate's open screen
stop(); //makes the screen wait for events
paraBtn.addEventListener(MouseEvent.CLICK, playClicked); //this line is making your button an mouse click event
function playClicked(evt: MouseEvent): void { // now we are calling the event from this function and telling it to go to the next frame we labelled play
gotoAndStop("frame2");
// All rights of this music goes towards the makers of the game "Risk of Rain" which was made by Hapoo Games
}
FRAME 2 (Where the game actually starts)
stop();
// This plays the sound when left click is used
var spitSound: Sound = new Sound();
spitSound.load(new URLRequest("gunSound.mp3"));
//This plays the gameover sound when your lives reach 0
var overSound: Sound = new Sound();
overSound.load(new URLRequest("Gameover.mp3"));
//This plays the sound when you are hit
var etSound: Sound = new Sound();
etSound.load(new URLRequest("Urgh.mp3"));
//This sets the lives and points.
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimTurret);
var points: Number = 0;
var lives: Number = 3;
var target: MovieClip;
var _health: uint = 100;
initialiseCursor();
//This variable stops the multiple errors with the move objects and bullets and range to stop compiling.
var Gameover: Boolean = false;
//This aims the turrent to where you mouse is on the screen
function aimTurret(evt: Event): void {
if (Gameover == false) {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance: Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance: Number = distance / 12 - 7;
}
}
function getAngle(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var radians: Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var dx: Number = x2 - x1;
var dy: Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad: Number): Number {
return rad * (180 / Math.PI);
}
//Starts lives and shows text next to the numbers
function initialiseCursor(): void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
livesdisplay.text = String(lives) + " Lives Left";
pointsdisplay.text = String(points) + " Points";
}
function targetMove(evt: MouseEvent): void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt: MouseEvent): void {
target.gotoAndStop(2);
}
function targetUp(evt: MouseEvent): void {
target.gotoAndStop(1);
}
//Starts bullets and speed of bullets, also addding new arrays for baddies
var gunLength: uint = 90;
var bullets: Array = new Array();
var bulletSpeed: uint = 20;
var baddies: Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
function fireGun(evt: MouseEvent) {
if (Gameover == false) {
var bullet: Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
spitSound.play();
}
}
function deg2rad(deg: Number): Number {
return deg * (Math.PI / 180);
}
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function moveObjects(evt: Event): void {
if (Gameover == false) {
moveBullets();
moveBaddies();
}
}
function moveBullets(): void {
for (var i: int = 0; i < bullets.length; i++) {
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x < -bullets[i].width || bullets[i].x > stage.stageWidth + bullets[i].width || bullets[i].y < -bullets[i].width || bullets[i].y > stage.stageHeight + bullets[i].width) {
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
// This is the start of the timer
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
// Adding army men on a timer and only from the top side
function addBaddie(evt: TimerEvent): void {
var baddie: Baddie = new Baddie();
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = -baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
function moveBaddies(): void {
for (var i: int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
//If baddie was removed then we don’t check for bullet hits
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie: Baddie): void {
for (var i: int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
points++;
if (points == 50) {
gotoAndStop("frame3")
}
pointsdisplay.text = String(points) + " Points";
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
// Keeping track of lost lives and when hitting 0 doing to frame four, also displaying "Lose life!"
function loseLife(): void {
etSound.play();
lives--;
if (lives == 0) {
Gameover = true;
overSound.play();
gotoAndStop("frame4")
}
livesdisplay.text = String(lives) + " Lives Left";
trace("Lose Life!");
}
FRAME 3 (This is where I need help, to add another movie clip) (I have made one for the frame named, "BaddieRed" With the Linkage being "Baddiered"
stop();
// The code from frame2 carries over and works the same in this frame
FRAME 4 (This is the screen where it's gameover)
stop();
timer.stop();
// User need to close by pressing the close button
//And restart the game manually

Is this what you're trying to achieve? Something like...
function addBaddie(evt: TimerEvent): void
{
var baddie : MovieClip;
if (points < 50) { var bad1: Baddie = new Baddie(); baddie = bad1; }
if (points >= 50) { var bad2 : Baddiered = new Baddiered(); baddie = bad2; }
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y -= baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}

Related

AS3 random symbol movement loop with easing?

I have cobbled together a script for making a movie symbol randomly move around the stage. My aim is to make it slowly hover around in one spot.
Problem is that it's pretty buggy and the position of the symbol always starts in the top left of the stage. I would really like to find a way to add easing into the script too.
Any help would be greatly appreciated!
//Declare Globals
var currentFrameCount: int = 300;
var totalFrameCount: int = 300;
this.x = Math.round(Math.random() * 200);
this.y = Math.round(Math.random() * 200);
var destinationX: Number = this.x;
var destinationY: Number = this.y;
var initialX: Number;
var initialY: Number;
var distanceX: Number;
var distanceY: Number;
var xProg: Number;
var yProg: Number;
var countFrame: int = 0;
var delay: int = 0;
addEventListener(Event.ENTER_FRAME, callDelay);
function callDelay(e: Event) {
countFrame++;
delayEvent(delay);
}
//Code to move the object to a random location and give it a random target to move to.
function spawnObject() {
destinationX = Math.round(Math.random() * 200); //random destination
destinationY = Math.round(Math.random() * 200);
currentFrameCount = 30;
initialX = this.x;
initialY = this.y;
distanceX = destinationX - initialX; //distance between destination and initial
distanceY = destinationY - initialY;
yProg = distanceY / totalFrameCount;
}
function delayEvent(period) {
if ((countFrame) >= period) {
removeEventListener(Event.ENTER_FRAME, callDelay);
timedEvent();
countFrame = 0;
return;
}
}
function timedEvent(): void {
currentFrameCount = totalFrameCount;
this.x = destinationX;
this.y = destinationY;
spawnObject(); //move the object to a new location and give new destination
this.addEventListener(Event.ENTER_FRAME, moveTo); //add an event listener to move the object around
}
function moveTo(e: Event): void {
currentFrameCount++;
if (currentFrameCount < totalFrameCount) {
this.x += xProg; //incrase x by the x step value
this.y += yProg; //increase y by the y step value
} else {
this.removeEventListener(Event.ENTER_FRAME, moveTo); // remvoe this event listener
addEventListener(Event.ENTER_FRAME, callDelay);
}
}

Player spazzes all over the area when doubled clicked

When the player is doubled clicked, he spazzes around the map. How do I prevent this?
This is the code I'm using to control the player:
stage.addEventListener(MouseEvent.CLICK, myClickReaction);
// speeds ALONG NYPOTENUSE
var v:Number = 7;
// vector of movement
var dir:int = 100;
// mouse click point
var clickPoint:Point = new Point();
// angle doesn't change metween clicks - so it can be global
var angle:Number;
function myClickReaction (e:MouseEvent):void {
clickPoint = new Point(mouseX, mouseY);
angle = Math.atan2(clickPoint.y - penguin.y, clickPoint.x - penguin.x);
dir = angle >= 0 ? -1 : 1;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onEnterFrame(e:Event):void {
var projectedX:Number = penguin.x + v * Math.cos(angle);
var projectedY:Number = penguin.y + v * Math.sin(angle);
var diff:Number = clickPoint.y - projectedY;
if (diff / Math.abs(diff) == dir) {
penguin.x = clickPoint.x;
penguin.y = clickPoint.y;
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
else {
penguin.x = projectedX;
penguin.y = projectedY;
}
}

catcher game lives won't update as3.0

I am trying to create a simple catcher game. I have the basic structure/logic figured out but I am facing some problems. For some reason the lives are not updating as I want them to. The only time they actually do work is when a "good" crane exits the screen at the top, then they decrease by one. But other than that (catch a "bad" crane or catch a "plus" crane) is not decreasing or increasing it by one. Similarly, the score seems to work for the "good" crane, adding the amount of score I specify, but not for the "bad" or the "plus" cranes.
What am I missing? Help!
package
{
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.*;
public class CatchingCranes extends MovieClip
{
//Define the variables
var catcher:CloudCatcher;
var nextCrane:Timer;
var objects:Array = new Array();
var score:int = 0;
var timer:Number;
var maxCount:Number = 60;
var totalLives:int = 5;
var CirclesArray:Array = [];
var spacer:int = 5;
var startPosition:int = 415;
var speed:Number = -7.0;
public function CatchingCranes()
{
createTimer();
createCatcher();
setNextCrane();
progressLevels();
addEventListener(Event.ENTER_FRAME, moveCranes);
}
//Function to indicate level progression
public function progressLevels()
{
status_mc.status_txt.text = "LEVEL ONE";
status_mc.instructions_txt.text = "COLLECT AT LEAST 500 POINTS";
if (score == 500)
{
status_mc.status_txt.text = "LEVEL TWO";
status_mc.instructions_txt.text = "COLLECT AT LEAST 750 POINTS";
goToLevelTwo();
}
if (score == 750)
{
status_mc.status_txt.text = "LEVEL THREE";
status_mc.instructions_txt.text = "COLLECT AT LEAST 1000 POINTS";
goToLevelThree();
}
if (score == 1000)
{
status_mc.status_txt.text = "CONGRATULATIONS";
status_mc.instructions_txt.text = "YOU NOW HAVE ONE WISH TO MAKE";
goToWin();
}
if (totalLives == 0)
{
status_mc.status_txt.text = "GAME OVER";
status_mc.instructions_txt.text = "CLICK TO TRY AGAIN";
goToLoose();
}
}
//Function to create a timer
public function createTimer()
{
var myTimer:Timer = new Timer(1000,maxCount);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();
function countdown(event:TimerEvent):void
{
timer = (maxCount)-myTimer.currentCount;
timer_txt.text = "TIME LEFT: " + String(timer);
if (timer <= 0)
{
trace("Time's Up");
myTimer.removeEventListener(TimerEvent.TIMER, countdown);
}
}
}
//Function to create the catcher
public function createCatcher()
{
catcher = new CloudCatcher();
catcher.y = 50;
catcher.x = 350;
addChild(catcher);
}
//Function to initiate the next crane production
public function setNextCrane()
{
nextCrane = new Timer(750+Math.random()*1000,1);
nextCrane.addEventListener(TimerEvent.TIMER_COMPLETE, newCrane);
nextCrane.start();
}
//Function to create a new crane
public function newCrane(event:Event)
{
//Array definition holding different kinds of cranes
var goodCranes:Array = ["ColorCrane1","ColorCrane2","ColorCrane3","ColorCrane4","ColorCrane5"];
var evilCranes:Array = ["EvilCrane"];
var silverCranes:Array = ["SilverCrane"];
var goldCranes:Array = ["GoldCrane"];
//Create a random number and check whether or not it is less than 0.9 (90 percent probability)
if (Math.random() < 0.9)
{
//Create good cranes
var r:int = Math.floor(Math.random() * goodCranes.length);
var classRef:Class = getDefinitionByName(goodCranes[r]) as Class;
var newCrane:MovieClip = new classRef();
newCrane.typestr = "good";
}
else
{
//Create a random number and check whether or not it is more than 0.9 (10 percent probability)
//Check to see if the current lives count is less than or equal to four, if it is
if (totalLives <= 4)
{
//Create cranes that provide user with an additional life
var p:int = Math.floor(Math.random() * silverCranes.length);
classRef = getDefinitionByName(silverCranes[p]) as Class;
newCrane = new classRef();
newCrane.typstr = "plus";
//Create cranes that are evil
var s:int = Math.floor(Math.random() * evilCranes.length);
classRef = getDefinitionByName(evilCranes[s]) as Class;
newCrane = new classRef();
newCrane.typstr = "bad";
}
else
{
//If lives are equal to five, only create the evil cranes
r = Math.floor(Math.random() * evilCranes.length);
classRef = getDefinitionByName(evilCranes[r]) as Class;
newCrane = new classRef();
newCrane.typstr = "bad";
}
}
//Specify the x and y location of the cranes
newCrane.x = Math.random() * 700;
newCrane.y = 500;
//Add crane
addChildAt(newCrane, 0);
objects.push(newCrane);
setNextCrane();
}
//Function to move the cranes up the stage
public function moveCranes(event:Event)
{
for (var i:int = objects.length-1; i>=0; i--)
{
//Make the catcher follow the position of the mouse
catcher.x = mouseX;
//Specify the crane's speed
objects[i].y += speed;
//If the object exits the top stage boundaries
if (objects[i].y < 0)
{
//Remove the child and take it out of the array
removeChild(objects[i]);
objects.splice(i,1);
//If that object is good
if (objects[i].typestr == "good")
{
//Remove one life from the user
totalLives = totalLives - 1;
trace(totalLives);
}
}
//Check to see if the crane collides with the cloud, if it does
if (objects[i].hitTestObject(catcher))
{
//And the crane is good
if (objects[i].typestr == "good")
{
//Add 25 to the score
score += 25;
}
//And the crane adds a life
if (objects[i].typestr == "plus")
{
//Add 10 to the score and increase lives by one
score += 10;
totalLives = totalLives + 1;
}
//And the crane is evil
if (objects[i].typestr == "bad")
{
//Take out 5 from the score and remove a life
score -= 5;
totalLives = totalLives - 1;
}
//If the score is less than zero, take it back to zero
if (score < 0)
{
score = 0;
}
//Remove the cranes and splice them from the array
removeChild(objects[i]);
objects.splice(i,1);
}
}
//Update the score display text and the lives with the correct values
score_display.text = "Score = " + score;
lives_txt.text = "Lives: " + totalLives;
}
//Functions to specify next level options and win/loose scenarios
function goToLevelTwo():void
{
}
function goToLevelThree():void
{
}
function goToWin():void
{
}
function goToLoose():void
{
}
}
}

AS3: Child object not displaying even when added

Ok, let me start off by saying that this is my first AS3 project. I'm ok with Java, so OOP and inheritance aren't new to me.
I have literally spent hours sitting here and pondering why my code isn't working like I wanted it to.
I'm starting off with a turret trying to shoot a bullet. However, the bullet isn't being drawn onto the screen, even though the x and y coords are still changing.
The method where the bullet/projectile is created is called OnMouseClick.
Here's my code:
public class Main extends Sprite
{
public var projectileArr : Array = new Array(); //array which the projectile objects are stored
public var projCount : Number = 0; //projectile counter
public var curX:Number; //mouse coords
public var curY:Number;
private var tri1:Sprite = new Sprite();
private var tri1Height:Number = 50;
private var rect1:Sprite = new Sprite();
private var rect1W:Number = 2;
private var rect1H:Number = 10;
private var angle:Number = 0;
private var acceleration:Number = 0;
public var triSpeedX:Number = 0;
public var triSpeedY:Number = 0;
public var turretAngle:Number ;
//keyboard booleans
private var leftDown:Boolean = false, rightDown:Boolean = false, upDown:Boolean = false, downDown:Boolean = false;
public function Main():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
//draw triangle
addChild(tri1);
tri1.graphics.lineStyle(1, 0xff00ff00);
tri1.graphics.beginFill(0xff0000);
tri1.graphics.moveTo(0, -tri1Height / 2)
tri1.graphics.lineTo(tri1Height / 3, +tri1Height / 2);
tri1.graphics.lineTo(-tri1Height / 3, +tri1Height / 2);
tri1.graphics.endFill();
tri1.x = 400;
tri1.y = 300;
//draw turret
addChild(rect1);
rect1.graphics.beginFill(0xFFFFFF);
rect1.graphics.moveTo(rect1W / 2, -rect1H);
rect1.graphics.lineTo(rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, 0);
rect1.graphics.lineTo(-rect1W / 2, -rect1H);
rect1.graphics.endFill();
rect1.x = tri1.x;
rect1.y = tri1.y;
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(Event.ENTER_FRAME, Run);
stage.addEventListener(MouseEvent.MOUSE_MOVE, getMouseCoord);
stage.addEventListener(MouseEvent.MOUSE_DOWN, OnMouseClick);
}
//creation of projectile on click
public function OnMouseClick (e:MouseEvent):void
{
projectileArr[projCount] = new Projectile (rect1.x, rect1.y, turretAngle); //create a new projectile object
addChild(projectileArr [projCount]); //... then it doesn't display
projCount++;
trace ("BAM");
}
public function getMouseCoord(e:MouseEvent):void
{
curX = mouseX;
curY = mouseY;
}
public function onUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = false;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = false;
if (e.keyCode == Keyboard.UP)
upDown = false;
else if (e.keyCode == Keyboard.DOWN)
downDown = false;
}
public function onDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.LEFT)
leftDown = true;
else if (e.keyCode == Keyboard.RIGHT)
rightDown = true;
if (e.keyCode == Keyboard.UP)
upDown = true;
else if (e.keyCode == Keyboard.DOWN)
downDown = true;
}
public function addProjToScreen (projectile:Projectile) : void
{
addChild(projectile);
}
private function Run(e:Event):void
{
acceleration = 0; //resets acceleration back to 0 to limit speed
if (leftDown)
{
angle -= 5;
}
else if (rightDown)
{
angle += 5;
}
if (upDown)
{
acceleration += 3;
}
else if (downDown)
{
acceleration -= 3;
}
triSpeedX += acceleration * Math.cos(angle * Math.PI / 180);
triSpeedY += acceleration * Math.sin(angle * Math.PI / 180);
tri1.x += triSpeedX;
tri1.y += triSpeedY;
//borders
if (tri1.x < 0)
{
triSpeedX *= -.5;
tri1.x = 0 ;
}
if (tri1.x > 800 )
{
tri1.x = 800;
triSpeedX *= -.5;
}
if (tri1.y < 0)
{
triSpeedY *= -.5;
tri1.y = 0 ;
}
if (tri1.y > 600)
{
triSpeedY *= -.5;
tri1.y = 600;
}
//friction
triSpeedX *= 0.95
triSpeedY *= 0.95
rect1.x = tri1.x;
rect1.y = tri1.y;
var xCurDist:Number = curX - rect1.x;
var yCurDist:Number = curY - rect1.y;
turretAngle = Math.atan(yCurDist / xCurDist) * 180 / Math.PI ;
if (xCurDist < 0 )
{
turretAngle += 180;
}
if (xCurDist > 0 && yCurDist < 0 )
{
turretAngle += 360;
}
rect1.rotation= turretAngle + 90; // + 90 to account for the sprite originally pointing up, which is 270 degrees ccw
tri1.rotation = angle + 90;
for (var i:int = 0 ; i < projCount ; i ++)
{
projectileArr [i].move();
}
}
}
and the Projectile class:
public class Projectile extends MovieClip
{
private var projectile : Sprite = new Sprite();
private var speed: int = 10;
private var angle :Number;
private var xIncr: Number;
private var yIncr: Number;
public function Projectile(x:Number, y:Number, angle:Number)
{
this.x = x;
this.y = y;
this.angle = angle;
projectile.graphics.beginFill (0xFF0000);
projectile.graphics.drawCircle (x, y, 4);
projectile.graphics.endFill() ;
xIncr = speed * Math.cos (angle); // angle needs to be converted to radians
yIncr = speed * Math.sin (angle);
}
public function move () :void
{
trace (this.x + " " + this.y);
this.x += xIncr;
this.y += yIncr;
}
}
I just don't know what I'm missing... I'm calling addChild to all of my newly created objects, what else is there to do?
You are not adding the sprite projectile to the displaylist of Projectile in your constructor.
addChild(projectile);
Also you are doubling up on x and y co-ordinates in your projectile class. Rectify this by changing projectile.graphics.drawCircle (x, y, 4); to projectile.graphics.drawCircle (0, 0, 4);

AS2 code to AS3 code help converting!

Help!!! This as2 code has given me a mind numbing headache. Can someone help me convert it to AS3. Here is the code:
import flash.filters.GlowFilter;
//Settings
var maxDist:Number = 400;
var accuracy:Number = 1;
//other vars (do not edit)
var dx:Number;
var dy:Number;
var startX:Number;
var startY:Number;
var endX:Number;
var endY:Number;
var realDist:Number;
var rad:Number = Math.PI/180;
var rad2:Number = 180/Math.PI;
map_mc.createEmptyMovieClip("laser_mc", map_mc.getNextHighestDepth());
//Glow Filter
var glow:GlowFilter = new GlowFilter();
glow.color = 0xFF0000;
glow.alpha = 1;
glow.blurX = 7;
glow.blurY = 7;
glow.quality = 2;
map_mc.laser_mc.filters = new Array(glow);
/**
*
* Mouse Controls
*
*/
//create an object that we'll listen to
mouseListener = new Object();
//on Click, fire the weapon
mouseListener.onMouseDown = function() {
fireWeapon();
}
//on release, stop weapon firing
mouseListener.onMouseUp = function() {
stopWeapon();
}
//on mouse move, rotate the player
mouseListener.onMouseMove = function() {
rotatePlayer();
}
//add listener
Mouse.addListener(mouseListener);
/**
*
* Laser Weapon
*
*/
//fire weapon function - creates an onEnterFrame function to repeat updateLaser() over and over
function fireWeapon():Void
{
_root.onEnterFrame = function ():Void {
updateLaser();
}
}
//stop weapon function - deletes onEnterFrame and clears laser movieclip
function stopWeapon():Void
{
delete _root.onEnterFrame;
map_mc.laser_mc/**/.clear();
}
//Update Laser Function
function updateLaser() :Void
{
//run a loop
for (realDist=0; realDist<maxDist; realDist += accuracy)
{
//get end X&Y
endX = map_mc.player_mc._x + Math.cos(map_mc.player_mc._rotation * rad) * realDist;
endY = map_mc.player_mc._y + Math.sin(map_mc.player_mc._rotation * rad) * realDist;
//calculate hit test
if (map_mc.walls_mc.hitTest(endX, endY, true)) {
break;
}
}
//calculate the tip of the barrel (start X & Y)
startX = map_mc.player_mc._x + 15 * Math.cos(map_mc.player_mc._rotation * rad);
startY = map_mc.player_mc._y + 15 * Math.sin(map_mc.player_mc._rotation * rad);
// Clear it before we draw, so the line doesnt stay there
map_mc.laser_mc.clear();
//draw laser
map_mc.laser_mc.lineStyle(2, 0xFF0000, 75);
map_mc.laser_mc.moveTo(startX, startY);
map_mc.laser_mc.lineTo(endX, endY);
}
//rorate player towards mouse function
function rotatePlayer():Void
{
//get distance between mouse and player
dx = map_mc._xmouse-map_mc.player_mc._x;
dy = map_mc._ymouse-map_mc.player_mc._y;
//calculate rotation of player
map_mc.player_mc._rotation = Math.atan2(dy, dx)*rad2;
}
THX
Here is the bulk of it
You shouldn't get compile errors now
Plus I cleaned it up
You will also have to fix your rotation point of player_mc
import flash.filters.GlowFilter;
//Settings
var maxDist:Number = 400;
var accuracy:Number = 1;
//other vars (do not edit)
var dx:Number;
var dy:Number;
var startX:Number;
var startY:Number;
var endX:Number;
var endY:Number;
var realDist:Number;
var rad:Number = Math.PI/180;
var rad2:Number = 180/Math.PI;
var laser_mc:MovieClip = new MovieClip()
map_mc.addChild(laser_mc)
//Glow Filter
var glow:GlowFilter = new GlowFilter();
glow.color = 0xFF0000;
glow.alpha = 1;
glow.blurX = 7;
glow.blurY = 7;
glow.quality = 2;
laser_mc.filters = new Array(glow);
/**
*
* Mouse Controls
*
*/
stage.addEventListener( MouseEvent.MOUSE_DOWN, fire);
//on Click, fire the weapon
function fire( e:Event ):void {
stage.addEventListener( Event.ENTER_FRAME , updateLaser)
}
stage.addEventListener( MouseEvent.MOUSE_UP, stopFire);
//on release, stop weapon firing
function stopFire( e:Event ):void {
laser_mc.graphics.clear();
stage.removeEventListener( Event.ENTER_FRAME , updateLaser)
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoved)
//on mouse move, rotate the player
function mouseMoved( e:Event ):void {
//get distance between mouse and player
dx = map_mc.mouseX-map_mc.player_mc.x;
dy = map_mc.mouseY-map_mc.player_mc.y;
//calculate rotation of player
map_mc.player_mc.rotation = Math.atan2(dy, dx)*rad2;
}
//Update Laser Function
function updateLaser( e:Event ):void {
//run a loop
for (realDist=0; realDist<maxDist; realDist += accuracy){
//get end X&Y
endX = map_mc.player_mc.x + Math.cos(map_mc.player_mc.rotation * rad) * realDist;
endY = map_mc.player_mc.y + Math.sin(map_mc.player_mc.rotation * rad) * realDist;
//calculate hit test
if (map_mc.walls_mc.hitTestPoint(endX,endY)) {
break;
}
}
//calculate the tip of the barrel (start X & Y)
startX = map_mc.player_mc.x + 15 * Math.cos(map_mc.player_mc.rotation * rad);
startY = map_mc.player_mc.y + 15 * Math.sin(map_mc.player_mc.rotation * rad);
//draw laser
laser_mc.graphics.clear();
laser_mc.graphics.lineStyle(2, 0xFF0000);
laser_mc.graphics.moveTo(startX, startY);
laser_mc.graphics.lineTo(endX, endY);
}