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);
}
Related
I'm building a test avatar chat... thingy in ActionScript3, but I've come across a problem, whenever I click the chatbar to say something, my avatar (which is currently a penguin) walks to it -- how can I prevent this from happening? In other words, how do I build a wall and keep the penguins out?
This is the code I'm using to make my penguin move.
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;
}
}
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;
}
}
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);
}
I have a problem here and I have tried my best to figure out why I'm getting this error on Line 325. Here is the entire script. I'm using Flash CS5.5. Thank you for helping as I'm completely stuck. I changed the names of my movieClips but still the error persists. Thanks again.
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.utils.getTimer;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.system.fscommand;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.display.SimpleButton;
var loader:Loader = new Loader();
var file:URLRequest = new URLRequest("vermin-ator.swf");
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteLoad);
loader.load(file);
function onCompleteLoad (loadEvent:Event):void
{
addChild(loadEvent.currentTarget.content);
}
// player settings
var _rotateSpeedMax:Number = 20;
//private var _gravity:Number = .68;
// projectile gun settings
var _bulletSpeed:Number = 8;
var _maxDistance:Number = 300;
var _reloadSpeed:Number = 250; //milliseconds
var _barrelLength:Number = 20;
var _bulletSpread:Number = 5;
var score:int = 0;
// gun stuff - do not edit
var _isLoaded:Boolean = true;
var _isFiring:Boolean = false;
var _endX:Number;
var _endY:Number;
var _startX:Number;
var _startY:Number;
var _reloadTimer:Timer;
var _bullets:Array = [];
// array that holds walls
//var _solidObjects:Array = [];
//array for rifle sounds
var mySoundArray:Array = [];
var mySoundRandom:Number;
//game scorings
//var myFormat:TextFormat = new TextFormat();
// myFormat.size = 20;
//var gameScoreField:TextField;
//var gameScore:int;
// gameScore = 0;
// var myText_txt:TextField = new TextField();
// global vars
var player:MovieClip;
//var _player2:MovieClip;
//var _player3:MovieClip;
var _dx:Number;
var _dy:Number;
var _pcos:Number;
var _psin:Number;
var _trueRotation:Number;
var count:Number;
var dougie:MovieClip;
var murphy:MovieClip;
var dougieTalk:MovieClip;
var murphyTalk:MovieClip;
var murphyScream:MovieClip;
var newRabbit:MovieClip;
var tempBullet:MovieClip;
var bullet_mc:MovieClip;
//how much time before another rabbit is made
var rabbitTime:int = 0;
//how much time is needed to make a rabbit
var rabbitLimit:int = 16;
//this movieclip holds the bullets
//var bulletContainer:MovieClip = new MovieClip();
//addChild(bulletContainer)
var soundOn:Boolean = true;
//var myTransform:SoundTransform;
//variable for rifle sound
var rifle1Sound:Sound = new rifle1sound();
//variable for rifle sound
var rifle2Sound:Sound = new rifle2sound();
//variable for rifle sound
var rifle3Sound:Sound = new rifle3sound();
//variable for rifle sound
var rifle4Sound:Sound = new rifle4sound();
//variable for man laughing
//var manLaughSound:Sound = new manlaughsound();
//variable for man laughing
//var manPleasedSound:Sound = new manpleasedsound();
//varible for background sound
var bckgroundSound:Sound = new bckgroundsound();
//varible for rabbit shot sound
//var rabbitSound:Sound = new rabbitsound();
//variable for button sound
var BtnSound:Sound = new buttonSound();
//make screen for Stop invisible
var stopScreen:MovieClip;
//make screen for Credits visible
var creditScreen:MovieClip;
//make screen for Rules visible
var rulesScreen:MovieClip;
murphyTalk.visible = true;
dougieTalk.visible = true;
dougie.visible = true;
murphy.visible = true;
murphyScream.visible = true;
creditScreen.visible = true;
rulesScreen.visible = true;
stopScreen.visible = false;
//enable hand cursors on mouse over over buttons
var movieClip_8:MovieClip;
var movieClip_9:MovieClip;
var movieClip_10:MovieClip;
var movieClip_11:MovieClip;
var newrabbit:MovieClip;
var closeGame:MovieClip;
//listener and function for how to play button
movieClip_10.addEventListener(MouseEvent.MOUSE_DOWN, helpScreen);
function helpScreen(evt:MouseEvent):void {
rulesScreen.visible=true;
}
//listener and function for how to play button
movieClip_9.addEventListener(MouseEvent.MOUSE_DOWN, ahelpScreen);
function ahelpScreen(evt:MouseEvent):void {
creditScreen.visible=true;
}
//Add event listeners for all 3 Over, Out and Down
movieClip_8.addEventListener(MouseEvent.MOUSE_OVER, mOver);
function mOver(e:MouseEvent):void {
murphyTalk.visible = false;
dougieTalk.visible = false;
dougie.visible = false;
murphy.visible = false;
murphyScream.visible= true;
}
movieClip_8.addEventListener(MouseEvent.MOUSE_OUT, mOut);
//Mouse methods
function mOut(e:MouseEvent):void {
murphyScream.visible= false;
removeChild(murphyTalk);
removeChild(dougieTalk);
removeChild(dougie);
removeChild(murphy);
//Remove all listeners
movieClip_8.removeEventListener(MouseEvent.MOUSE_OVER, mOver);
movieClip_8.removeEventListener(MouseEvent.MOUSE_OUT, mOut);
}
/**
* Constructor
*/
//public function Main()
/*recurring event listener for updates
addEventListener(Event.ENTER_FRAME,showGameScore);
function showGameScore() {
gameScoreField.text = "Game: "+String(gameScore);
addChild(gameScoreField); */
movieClip_8.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
function mDown(e:MouseEvent):void {
createPlayer();
// add listeners
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, `enter code here`onMouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
// add movieclips to solidObjects array
// will test for collisions with bullets
//
// *** movieclips are located on stage in the fla
//_solidObjects = [rabbit01, rabbit02, rabbit03, rabbit04];
//adding enemies to stage
if(rabbitTime < rabbitLimit){
//if time hasn't reached the limit, then just increment
rabbitTime ++;
} else {
//defining a variable which will hold the new enemy
//var newRabbit:MovieClip = new Rabbit();
//making the enemy offstage when it is created
newrabbit.s = -1 * newrabbit.width;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
newrabbit.x = int(Math.random()*(stage.stageWidth - newrabbit.width));
//then add the enemy to stage
addChild(newrabbit);
//and reset the enemyTime
rabbitTime = 0;
}
//////////////////////////////////////
// Player & Weapon Methods
//////////////////////////////////////
/**
* Creates player
* Uses "Player" movieclip linked in library
*/
function createPlayer():void
{
// attach player movieclip from library
player = new Player();
// position player in center
player.x = stage.stageWidth / 2;
//_player.y = stage.stageHeight / 2;
// add to display list
stage.addChild(player);
}
/**
* Reload timer
* #param e Takes TimerEvent
*/
function reloadTimerHandler(e:TimerEvent):void
{
// stop timer
e.target.stop();
// clear timer var
_reloadTimer = null;
reloadWeapon();
}
/**
* Fire weapon
*/
function fire():void
{
// check if firing
if (!_isFiring) return;
// check if reloaded
if (!_isLoaded) return;
// create bullet
createBullet();
// start reload timer
_reloadTimer = new Timer(_reloadSpeed);
_reloadTimer.addEventListener(TimerEvent.TIMER, `enter code here`reloadTimerHandler);
_reloadTimer.start();
// set reload flag to false
_isLoaded = false;
}
/**
* Creates a bullet movieclip and sets it's properties
*/
function createBullet():void
{
// precalculate the cos & sine
_pcos = Math.cos(player.rotation * Math.PI / 180);
_psin = Math.sin(player.rotation * Math.PI / 180);
// start X & Y
// calculate the tip of the barrel
_startX = player.x - _barrelLength * _pcos;
_startY = player.y - _barrelLength * _psin;
// end X & Y
// calculate where the bullet needs to go
// aim 50 pixels in front of the gun
_endX = player.x - 50 * _pcos + Math.random() * _bulletSpread - `enter code here`_bulletSpread * .5;
_endY = player.y - 50 * _psin + Math.random() * _bulletSpread - `enter code here`_bulletSpread * .5;
// attach bullet from library
var tempBullets:MovieClip = new Bullet();
// calculate velocity
tempBullets.vx = (_endX - _startX) / _bulletSpeed;
tempBullets.vy = (_endY - _startY) / _bulletSpeed;
// set position
tempBullets.x = _startX;
tempBullets.y = _startY;
// save starting location
tempBullets.startX = _startX;
tempBullets.startY = _startY;
// set maximum allowed travel distance
tempBullets.maxDistance = _maxDistance;
// add bullet to bullets array
_bullets.push(tempBullets);
// add to display list
stage.addChild(tempBullets);
}
/**
* Updates bullets
*/
function updateBullets():void
{
var i:int;
var tempBullets:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullets = _bullets[i];
// check if gravity is enabled
//if (gravityCheckbox.selected)
//{
// add gravity to Y velocity
//tempBullet.vy += _gravity;
}
// update bullet position
tempBullets.x += tempBullets.vx;
tempBullets.y += tempBullets.vy;
// check if bullet went too far
if (getDistance(tempBullets.startX - tempBullets.x, `enter code here`tempBullets.startY - tempBullets.y) > tempBullets.maxDistance + `enter code here`_barrelLength)
{
destroyBullet(tempBullets);
}
// check for collision with walls
if (checkCollisions(tempBullets.x, tempBullets.y))
{
destroyBullet(tempBullets);
}
}
/**
* Destroys bullet
* #param bullet Takes bullet movieclip
*/
function destroyBullet(bullet_mc:MovieClip):void
{
var i:int;
var tempBullets:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullets = _bullets[i];
// if found bullet in array
if (tempBullets == bullet_mc)
{
// remove from array
_bullets.splice(i, 1);
// remove from display list
_bullets.removeChild(bullet_mc);
// stop loop
return;
}
}
}
/**
* Reload weapon
*/
function reloadWeapon():void
{
_isLoaded = true;
}
/**
* Checks for collisions between points and objects in _solidObjects
* #return Collision boolean
*/
function checkCollisions(testX:Number, testY:Number):Boolean
{
//var i:int;
var newrabbit:MovieClip;
// loop thru _solidObjects array
//for (i = 0; i < _solidObjects.length; i++)
{
// save a reference to current object
//newRabbit = _solidObjects[i];
// do a hit test
if (newrabbit.hitTestPoint(testX, testY, true))
{
return true;
// stop loop
//break;
}
}
return false;
}
/**checking if Rabbits is touching any bullets
for(var i:int = 0;i<_root.bulletContainer.numChildren;i++){
//numChildren is the amount of movieclips within the bulletContainer.
//we define a variable that will be the bullet that we are currently
//hit testing.
var bulletTarget:MovieClip = _root.bulletContainer.getChildAt(i);
//now we hit test
if(hitTestObject(bulletTarget)){
//remove this from the stage if it touches a bullet
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
_root.removeChild(this);
//also remove the bullet and its listeners
_root.bulletContainer.removeChild(bulletTarget);
bulletTarget.removeListeners();
}
}*/
/**
* Calculate player rotation
*/
function updateRotation():void
{
// calculate rotation based on mouse X & Y
_dx = player.x - stage.mouseX;
_dy = player.y - stage.mouseY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > player.rotation + 90) rotateTo -= 180;
if (rotateTo < player.rotation - 90) rotateTo += 180;
// ease rotation
_trueRotation = (rotateTo - player.rotation) / _rotateSpeedMax;
// update rotation
player.rotation += _trueRotation;
}
//////////////////////////////////////
// Event Handlers
//////////////////////////////////////
/**
* Enter Frame handler
* #param event Uses Event
*/
function enterFrameHandler(event:Event):void
{
updateRotation();
updateBullets();
fire();
}
/**
* Mouse Up handler
* #param e Uses MouseEvent
*/
function onMouseUpHandler(event:MouseEvent):void
{
_isFiring = false;
//make bubble for Run Scream invisible
murphyScream.visible = false;
}
/**
* Mouse Down handler
* #param e Uses MouseEvent
*/
function onMouseDownHandler(event:MouseEvent):void
{
_isFiring = true;
//play random rifle sound from an array
var mySoundArray:Array = new Array(rifle1sound, rifle2sound, `enter code here`rifle3sound, rifle4sound);
`enter code here`mySoundArray[Math.floor(Math.random()*mySoundArray.length)].play();
}
//////////////////////////////////////
// Utilities
//////////////////////////////////////
/**
* Get distance
* #param delta_x
* #param delta_y
* #return
*/
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
/**
* Get radians
* #param delta_x
* #param delta_y
* #return
*/
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #param radians Takes radians
* #return Returns degrees
*/
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
movieClip_8.removeEventListener(MouseEvent.MOUSE_DOWN, mDown);
}
//listener and function for how to play button
movieClip_11.addEventListener(MouseEvent.MOUSE_DOWN, bhelpScreen);
function bhelpScreen(evt:MouseEvent):void {
stopScreen.visible=true;
}
closeGame.addEventListener(MouseEvent.MOUSE_DOWN, closeApp);
function closeApp(event:MouseEvent):void {
fscommand("quit");
}
Check that Bullet is also the class name on the library.
I want to create an object that follows and stops at mouse click. I managed to make it happen with rotation but the problem is that whenever i click on the empty stage, the object will move towards it and it carries on moving. It does not stop at the mouse location. Anyone know how i can do that. Below is my code:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Guest extends MovieClip
{
var walkSpeed:Number = 5;
public function Guest()
{
stage.addEventListener(MouseEvent.CLICK, walk);
}
function walk(event:MouseEvent):void
{
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(event:Event):void
{
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
stage.removeEventListener(Event.ENTER_FRAME, loop);
}
}
}
Your code is a bit weird, here you will never move towards position for more than one frame since you remove the event listener as soon as loop is done.
Here is some code that fixes the moving and then stopping issue. However I strongly suggests that you do this with some kind of "tweening library" and I will after this show an example of doing that with Caurina Transitions.
function walk(e:MouseEvent):void {
targetX = parent.mouseX; //targetX created as a member variable
targetY = parent.mouseY; //targetY created as a member variable
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(e:Event):void {
var newX:Number = x + Math.cos(rotation / 180 * Math.PI) * walkSpeed;
var newY:Number = y + Math.sin(rotation / 180 * Math.PI) * walkSpeed;
var atTarget:Boolean = true;
if (Math.abs(targetX - newX) > walkSpeed) {
x = newX;
atTarget = false;
}
if(Math.abs(targetY - y) > walkSpeed) {
y = newY;
atTarget = false;
}
if (atTarget) {
stage.removeEventListener(Event.ENTER_FRAME, loop);
}
}
Here's the same behaviour with caurina.
package
{
import caurina.transitions.Tweener;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class TransitionExample extends MovieClip
{
private var targetX:Number;
private var targetY:Number;
var walkSpeed:Number = 5;
public function TransitionExample()
{
trace("ctor()");
stage.addEventListener(MouseEvent.CLICK, walk);
}
private function walk(e:MouseEvent):void {
targetX = parent.mouseX;
targetY = parent.mouseY;
var dx = targetX - x;
var dy = targetY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
var tweenDone:Function = function():void {
trace("tween is finished");
}
//modify time to be dependant on the "walkspeed" and the distance travelled etc...
Tweener.addTween(this, { x:targetX, y:targetY, time:0.458, transition:"linear", onComplete:tweenDone});
}
}
}