AS3 How do I make these objects loop endlessly? - actionscript-3

Here is my code so far, I am trying to create a top down car game and here is the code I have so far, I am currently trying to get the cars to loop but I am struggling to find a way to do it, please try and help me out with the code or point me in the right direction if you can please and thank you in advance
import flashx.textLayout.utils.CharacterUtil;
var result:Number = Math.random() * 100
var randomX:Number = Math.random() * stage.stageWidth
var background = new Background;
var char = new Char();
var car1 = new Car1();
var car2 = new Car2();
var car3 = new Car3();
var car4 = new Car4();
car1.x = Math.random()* stage.stageWidth;
car2.x = Math.random()* stage.stageWidth;
car3.x = Math.random()* stage.stageWidth;
car4.x = Math.random()* stage.stageWidth;
background.x = 200;
char.x = 700/2;
car1.y = -0;
car2.y = -150;
car3.y = -300;
car4.y = -450;
background.y = 200;
char.y = 450;
addChild(background);
addChild(char);
addChild(car1);
addChild(car2);
addChild(car3);
addChild(car4);
char.gotoAndStop("car");
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler(event:Event):void
{
car1.y +=12;
car2.y +=12;
car3.y +=12;
car4.y +=12;
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_PressKeyToMove);
function fl_PressKeyToMove(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.RIGHT:
{
char.x += 15;
if (char.hitTestObject(barrier1))
{
char.x -=15 ;
}
break;
}
case Keyboard.LEFT:
{
char.x -= 15;
if (char.hitTestObject(barrier2))
{
char.x +=15 ;
}
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME, detectCollision);
function detectCollision(event:Event) {
if(char.hitTestObject(car1))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car2))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car3))
{
char.gotoAndStop("boom");
}
if(char.hitTestObject(car4))
{
char.gotoAndStop("boom");
}
}

If you're trying to get cars to reposition to the top of the screen as #onekidney guessed, you could easily do so by using the % operator:
function fl_EnterFrameHandler(event:Event):void
{
car1.y = (car1.y + 12) % stage.stageHeight;
car2.y = (car2.y + 12) % stage.stageHeight;
car3.y = (car3.y + 12) % stage.stageHeight;
car4.y = (car4.y + 12) % stage.stageHeight;
}
You can read more about the modulo operator in the documentation

Related

how to stop particles from moving off stage, Actionscript random particle generator

Below is some code for a random particle generator. I want to change it so the particles only move a small distance before stopping and not disappearing. As it is now, they keep moving until they go off stage. I'm new to Actionscript so any help would be appreciated, thanks.
var particleArray:Array = new Array();
var maxParticles:Number = 50000;
function addParticle(e:Event)
{
var Symbol:Symbol3 = new Symbol3();
Symbol.alpha = Math.random() * .8 + .2;
Symbol.scaleX = Symbol.scaleY = Math.random() * .8 + .2;
Symbol.xMovement = Math.random() * 10 - 5;
Symbol.yMovement = Math.random() * 10 - 5;
Symbol.x = mouseX;
Symbol.y = mouseY;
particleArray.push(Symbol);
addChild(Symbol);
Symbol.cacheAsBitmap = true;
if (particleArray.length >= maxParticles)
{
removeChild(particleArray.shift());
}
Symbol.addEventListener(Event.ENTER_FRAME,moveParticle);
}
function moveParticle(e:Event)
{
e.currentTarget.x += e.currentTarget.xMovement;
e.currentTarget.y += e.currentTarget.yMovement;
}
var myTimer:Timer = new Timer(50);
myTimer.addEventListener(TimerEvent.TIMER, addParticle);
myTimer.start();
One way to do this would be to remove the event listener after a number executions:
function addParticle(e:Event)
{
var Symbol:Symbol3 = new Symbol3();
Symbol.alpha = Math.random() * .8 + .2;
Symbol.scaleX = Symbol.scaleY = Math.random() * .8 + .2;
Symbol.xMovement = Math.random() * 10 - 5;
Symbol.yMovement = Math.random() * 10 - 5;
// set the number of times this instance can move.
// Using a randomly generated number here
Symbol.movementCount = int(Math.random() * 10);
Symbol.x = mouseX;
Symbol.y = mouseY;
particleArray.push(Symbol);
addChild(Symbol);
Symbol.cacheAsBitmap = true;
if (particleArray.length >= maxParticles)
{
removeChild(particleArray.shift());
}
Symbol.addEventListener(Event.ENTER_FRAME,moveParticle);
}
function moveParticle(e:Event)
{
e.currentTarget.x += e.currentTarget.xMovement;
e.currentTarget.y += e.currentTarget.yMovement;
// decrement your move count, and then check to see if it's hit zero
e.currentTarget.movementCount--;
if(e.currentTarget.movementCount <=0)
{
// if so, remove the event listener
e.currentTarget.removeEventListener(Event.ENTER_FRAME, moveParticle);
}
}

AS3 - Shooting Game - hitTestObject

i'm about to finish my project for University. But I'm stuck with the hittestobject.
var Player: gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e: MouseEvent): void
{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event: Event): void
{
var Bullet: bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
Bullet.x = Player.x;
Bullet.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(Bullet);
/* addChild(explosion);*/
Bullet.addEventListener(Event.ENTER_FRAME, moveBullet);
}
function release_shoot(event: Event): void
{
var explosion: explo1 = new explo1();
Player.rotationX = -5;
Player.rotationY = -5;
}
function moveBullet(e: Event): void
{
e.target.y -= 12;
e.target.x -= 96;
if (e.target.y <= -200 || e.target.x <= -200)
{
e.target.removeEventListener(Event.ENTER_FRAME, moveBullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event: Event): void
{
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event: Event): void
{
var bullet: MovieClip = MovieClip(event.target);
if (bullet.hitTestObject(mc_target))
{
mc_burst.x = mc_target.x;
mc_burst.y = mc_target.y;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550)
bullet.removeEventListener(Event.ENTER_FRAME, targeting);
else
bullet.y -= 12;
bullet.x -= 96;
}
The bullet is going in the Target without any doubt, I see it haha... But won't replace mc_target with mc_burst.
EDIT
This is the working code I used for anyone who's interested:
var Player:gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e:MouseEvent):void{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event:Event):void{
var bullet1:bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
bullet1.x = Player.x;
bullet1.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(bullet1);
/* addChild(explosion);*/
bullet1.addEventListener(Event.ENTER_FRAME, targeting);
}
function release_shoot(event:Event):void{
var explosion:explo1 = new explo1();
Player.rotationX =- 5;
Player.rotationY =- 5;
}
function movebullet(e:Event):void{
e.target.y -= 12;
e.target.x -=96;/*When the function is called the targets Y position will be subract by 40 pixels every frame, this makes the movieclip move up. The target is the Bullet movieclip.*/
if(e.target.y <= -200 && e.target.x <= -200 ){
e.target.removeEventListener(Event.ENTER_FRAME, movebullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event:Event):void {
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event:Event):void {
var bullet1:MovieClip = MovieClip(event.target);
if (bullet1.hitTestObject(mc_target)){
mc_burst.x = mc_target.y;
mc_burst.y = mc_target.x;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550){
bullet1.removeEventListener(Event.ENTER_FRAME, targeting);
}
else{
bullet1.y -= 12;
bullet1.x -= 96;}
}
// REPLACING CURSOR BY A SIGHT //
import flash.ui.Mouse;
Mouse.hide();
var myCursor:sight = new sight();
myCursor.visible = false;
function init()
{
addChild(myCursor);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OVER, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OUT, mouseMoveHandler);
}
function mouseMoveHandler(evt:MouseEvent):void
{
myCursor.visible = true;
myCursor.x = evt.stageX + 10;
myCursor.y = evt.stageY + 10;
}
function mouseLeaveHandler(evt:Event):void
{
myCursor.visible = false;
}
init();
Assuming the code you've posted is everything, the issue is that the targeting method is never called.
Seems like you want to add it as a handler for the enter frame event (as you are removing a listener to that end inside the method)
eg.
bulletInstance.addEventListener(Event.ENTER_FRAME, targeting);
That said, looking at your code, you're going to want to combine your move and targeting functions (you don't want to keep collision checking after you've removed the bullet in your moveBullet function) - or at least remove the targeting enter frame listener when you remove the button from the screen.
Possibly something like this:
function removeBullet(b:MovieClip):void {
b.removeEventListener(Event.ENTER_FRAME, moveBullet);
removeChild(MovieClip(b));
}
function moveBullet(e:Event):void {
var bullet:MovieClip = MovieClip(event.target);
bullet.y -= 12;
bullet.x -= 96;
if(bullet.y <= -200 || bullet.x <= -200 ){
removeBullet(bullet);
}
if (bullet.hitTestObject(mc_target)){
mc_burst.x = mc_target.x;
mc_burst.y = mc_target.y;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
removeBullet(bullet);
trace("targerting");
} else if (mc_target.x > 550){
removeBullet(bullet);
}
}
If you have many bullets, you'll probably want to have just one enter frame handler, and iterate through each bullet there - instead of having a separate enter frame handler for each bullet.
Also, I'm surprised you are not getting errors, because you have ambiguous naming going on. You have a class called bullet, but then you create vars called bullet as well. Standard practice in AS3 is the give your class names a capitol first letter, and your instance names a lowercase first letter. I'd recommend you do this to avoid errors and ambiguous code.
I would like to thanks BadFeelingAboutThis for his fast help here.
So for people who want to use my code, go head it works now
var Player:gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);
function mousemove(e:MouseEvent):void{
Player.x = mouseX + 200;
Player.y = mouseY + 35;
}
function shoot(event:Event):void{
var bullet1:bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
bullet1.x = Player.x;
bullet1.y = Player.y;
/* explosion.x = Player.x;
explosion.y = Player.y;*/
Player.rotationX = 5;
Player.rotationY = 5;
addChild(bullet1);
/* addChild(explosion);*/
bullet1.addEventListener(Event.ENTER_FRAME, targeting);
}
function release_shoot(event:Event):void{
var explosion:explo1 = new explo1();
Player.rotationX =- 5;
Player.rotationY =- 5;
}
function movebullet(e:Event):void{
e.target.y -= 12;
e.target.x -=96;/*When the function is called the targets Y position will be subract by 40 pixels every frame, this makes the movieclip move up. The target is the Bullet movieclip.*/
if(e.target.y <= -200 && e.target.x <= -200 ){
e.target.removeEventListener(Event.ENTER_FRAME, movebullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event:Event):void {
mc_target.x -= 2;
if (mc_target.x < -20)
mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);
function targeting(event:Event):void {
var bullet1:MovieClip = MovieClip(event.target);
if (bullet1.hitTestObject(mc_target)){
mc_burst.x = mc_target.y;
mc_burst.y = mc_target.x;
mc_burst.gotoAndPlay(2);
mc_target.x = 200;
mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
mc_target.x = 200;
trace("targerting");
}
else if (mc_target.x > 550){
bullet1.removeEventListener(Event.ENTER_FRAME, targeting);
}
else{
bullet1.y -= 12;
bullet1.x -= 96;}
}
// REPLACING CURSOR BY A SIGHT //
import flash.ui.Mouse;
Mouse.hide();
var myCursor:sight = new sight();
myCursor.visible = false;
function init()
{
addChild(myCursor);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OVER, mouseLeaveHandler);
stage.addEventListener(MouseEvent.ROLL_OUT, mouseMoveHandler);
}
function mouseMoveHandler(evt:MouseEvent):void
{
myCursor.visible = true;
myCursor.x = evt.stageX + 10;
myCursor.y = evt.stageY + 10;
}
function mouseLeaveHandler(evt:Event):void
{
myCursor.visible = false;
}
init();

1046 AS3 Compile Time Error

I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
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);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
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(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.

Stopping/removing everything then changing scene

I am making a shooting game and when i die it will not remove the child's it just freezes them on the screen. I would like to be able to stop all of the action then remove and change screens afterwards.
var gunLength:uint = 90;
var bullets:Array = new Array();
var bulletSpeed:uint = 20;
var baddies:Array = new Array();
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
var lives:Number = 0;
stop();
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimGun);
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function addBaddie(evt:TimerEvent):void {
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
} else if (side == 2) {
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
} else if (side == 3) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
} else if (side == 4) {
baddie.x = - baddie.width
baddie.y = Math.random() * stage.stageHeight;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = Math.ceil(Math.random() * 15);
addChild(baddie);
baddies.push(baddie);
}
function fireGun(evt:MouseEvent) {
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);
}
function moveObjects(evt:Event):void {
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;
}
}
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();
lives -= 1;
if(lives < 1){
gotoAndStop(1,"Dead");
for each(var gun:Gun in gun){
removeChild(gun)
}
lives--;
trace("Lives = " + lives);
}
} 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);
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
function loseLife():void {
}
function aimGun(evt:Event):void {
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);
}
function deg2rad(deg:Number):Number {
return deg * (Math.PI/180);
}
var target:MovieClip;
initialiseCursor();
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);
}
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);
}

Actionscript 3 Score count on hitTestObject

I've been working on this simple car game in Flash CS5. The car has to avoid the cars coming vertically and pick up coins. I have three types of coins which add 1, 2 and 3 score points on being picked up. My problem is that when I hit the coin with the car it goes through the car and gives much more points. I also have problem with removing it from the stage... Here the code so far:
var spex:Number = 0;
var spey:Number = 4;
var score:uint;
var cars:Array = new Array ;
var db:Number = 2;
var db_coins:Number = 1;
var i:Number = 0;
for (i=0; i<=db; i++)
{
var traffic_mc:MovieClip = new traffic ;
cars.push(addChild(traffic_mc));
cars[i].x = -500 * Math.random();
cars[i].y = Math.random() * 400;
trace(cars[i].y);
}
for (i=0; i<=db_coins; i++)
{
var coin_y:MovieClip = new coin_yellow ;
coin_y.x = -500 * Math.random();
coin_y.y = Math.random() * 400;
addChild(coin_y);
var coin_r:MovieClip = new coin_red ;
coin_y.x = -500 * Math.random();
coin_y.y = Math.random() * 400;
addChild(coin_r);
var coin_b:MovieClip = new coin_blue ;
coin_b.x = -500 * Math.random();
coin_b.y = Math.random() * 400;
addChild(coin_b);
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(k:KeyboardEvent):void
{
if (k.keyCode == 37)
{
spex -= 4;
}
if (k.keyCode == 39)
{
spex += 4;
}
}
stage.addEventListener(Event.ENTER_FRAME, go);
function go(e:Event):void
{
this.auto.x += spex;
if (this.auto.x < 25)
{
this.auto.x = 25;
spex = 0;
}
if (this.auto.x > 286)
{
this.auto.x = 286;
spex = 0;
}
for (i=0; i<=db; i++)
{
if (cars[i].hitTestObject(this.auto))
{
trace("GAME OVER");
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keydown);
stage.removeEventListener(Event.ENTER_FRAME, go);
stage.addEventListener(KeyboardEvent.KEY_DOWN, retry);
}
cars[i].y += spey;
if (cars[i].y > 600)
{
cars[i].y = -50;
cars[i].x = Math.random() * 251;
}
}
for (i=0; i<=db_coins; i++)
{
if (coin_y.hitTestObject(this.auto))
{
score += 1;
updateScore();
}
coin_y.y += spey-2;
if (coin_y.y > 600)
{
coin_y.y = -50;
coin_y.x = Math.random() * 251;
}
if (coin_r.hitTestObject(this.auto))
{
score += 2;
updateScore();
}
coin_r.y += spey-2;
if (coin_r.y > 600)
{
coin_r.y = -50;
coin_r.x = Math.random() * 251;
}
if (coin_b.hitTestObject(this.auto))
{
score += 3;
updateScore();
}
coin_b.y += spey-2;
if (coin_b.y > 600)
{
coin_b.y = -50;
coin_b.x = Math.random() * 251;
}
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, retry);
function retry(k:KeyboardEvent):void
{
if (k.keyCode == 32)
{
stage.addEventListener(Event.ENTER_FRAME, go);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
for (i=0; i<=db; i++)
{
cars[i].y = -300 * Math.random();
cars[i].x = Math.random() * 251;
}
for (i=0; i<=db_coins; i++)
{
coin_y.y = -300 * Math.random();
coin_y.x = Math.random() * 251;
coin_r.y = -300 * Math.random();
coin_r.x = Math.random() * 251;
coin_b.y = -300 * Math.random();
coin_b.x = Math.random() * 251;
}
spex = 0;
spey = 4;
score = 0;
scorecounter.text = "Score: " + score.toString();
}
}
//Scorecount
function init():void
{
score = 0;
scorecounter.text = "Score: " + score.toString();
}
function updateScore():void
{
scorecounter.text = "Score: " + score.toString();
}
init();
i think you should create a variable like hited:Boolean and check first hit. Coin issue occurs cause coin isn't hitting for one time, it is hitting for a while cause every frame you move it and with movement it hits again. So you have to check it and make a proper "if-else" condition.
There is a better solution than the one you decided to use. spex is the variable that you are using to scroll the game. When you run your hitTestObject on the car simply put spex = 0; This will stop the game dead.
I agree with mitim to use removeChild() for the coins instead of just piling them up off stage.