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.
Related
I'm currently using this particle system and it work fine. Particle's should be destroy after cross boundry's or alpha's smaller then 0. But however sometimes when i use this code like pereatly 4 it fails and particles cant destory.
function init():void
{
particleArray = [];
addEventListener(Event.ENTER_FRAME, onEnterFrameLoop);
createParticle(s3.whell.x,s3.whell.y);
}
function onEnterFrameLoop(event:Event):void
{
updateParticle();
}
/**
* createParticle(target X position, target Y position)
*/
function createParticle(targetX:Number, targetY:Number):void
{
//run for loop based on particleTotal
for (var i:Number = 0; i < particleTotal; i++)
{
var particle_mc:MovieClip = new Particle();
//set position & rotation, alpha
particle_mc.x = targetX
particle_mc.y = targetY
particle_mc.rotation = Math.random() * 360;
particle_mc.alpha = Math.random() * 1.1;
//set particle boundry
particle_mc.boundyLeft = targetX - particleRange;
particle_mc.boundyTop = targetY - particleRange;
particle_mc.boundyRight = targetX + particleRange;
particle_mc.boundyBottom = targetY + particleRange;
//set speed/direction of fragment
particle_mc.speedX = Math.random() * particleMaxSpeed - Math.random() * particleMaxSpeed;
particle_mc.speedY = Math.random() * particleMaxSpeed - Math.random() * particleMaxSpeed;
particle_mc.speedX *= particleMaxSpeed
particle_mc.speedY *= particleMaxSpeed
//set fade out speed
particle_mc.fadeSpeed = Math.random()*particleFadeSpeed;
//just a visual particle counter
particleCurrentAmount++;
// add to array
particleArray.push(particle_mc);
// add to display list
addChild(particle_mc);
}
}
function updateParticle():void
{
for (var i = 0; i < particleArray.length; i++)
{
var tempParticle:MovieClip = particleArray[i];
//update alpha, x, y
tempParticle.alpha -= tempParticle.fadeSpeed;
tempParticle.x += tempParticle.speedX;
tempParticle.y += tempParticle.speedY;
// if fragment is invisible remove it
if (tempParticle.alpha <= 0)
{
destroyParticle(tempParticle);
}
// if fragment is out of bounds, increase fade out speed
else if (tempParticle.x < tempParticle.boundyLeft ||
tempParticle.x > tempParticle.boundyRight ||
tempParticle.y < tempParticle.boundyTop ||
tempParticle.y > tempParticle.boundyBottom)
{
tempParticle.fadeSpeed += 8;
destroyParticle(tempParticle);
}
}
}
function destroyParticle(particle:MovieClip):void
{
for (var i = 0; i < particleArray.length; i++)
{
var tempParticle:MovieClip = particleArray[i];
if (tempParticle == particle)
{
particleCurrentAmount--;
particleArray.splice(i,1);
removeChild(tempParticle);
}
}
}
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
I'm trying to complete background in kind of Space Invaders game. I want to generate stars at a random location, scroll them to the bottom of the stage and then add new star after each one is gone. I guess that the problem lies on the indexOf method, which I tried to use to find star y proprety.
I know this may be a stupid mistake, i'm a beginner :)
My current main class:
public class Main extends Sprite
{
private var ship:Ship = new Ship();
private var numStars:int = 80;
private var starArray:Array = new Array();
public function Main():void
{
stage.addChild(ship);
ship.x = stage.stageWidth / 2 - ship.width / 2;
ship.y = stage.stageHeight / 2 - ship.height / 2;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
for (var i:int = 0; i < numStars; i++)
{
createStar();
}
}
public function createStar():void
{
var newStar:Star = new Star();
starArray.push(newStar);
stage.addChildAt(newStar,1);
newStar.x = Math.random() * stage.stageWidth;
newStar.y = Math.random() * stage.stageHeight;
newStar.alpha = Math.random();
newStar.rotation = Math.random()*360;
newStar.scaleX = Math.random();
newStar.scaleY = Math.random();
}
public function keyDownHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP)
{
ship.accelerationY = -0.3;
}
if (e.keyCode == Keyboard.DOWN)
{
ship.accelerationY = 0.3;
}
if (e.keyCode == Keyboard.LEFT)
{
ship.accelerationX = -0.3;
}
if (e.keyCode == Keyboard.RIGHT)
{
ship.accelerationX = 0.3;
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.UP || e.keyCode == Keyboard.DOWN)
{
ship.accelerationX = 0;
ship.accelerationY = 0;
}
if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT)
{
ship.accelerationY = 0;
ship.accelerationX = 0;
}
}
public function enterFrameHandler(e:Event):void
{
//acceleration
ship.vx += ship.accelerationX;
ship.vy += ship.accelerationY;
//friction
ship.vx *= ship.friction;
ship.vy *= ship.friction;
if (Math.abs(ship.vx) < 0.1)
{
ship.vx = 0;
}
if (Math.abs(ship.vy) < 0.1)
{
ship.vy = 0;
}
ship.rotation = ship.vx * 2;
//set speed limit
if (ship.vx > ship.speedLimit)
{
ship.vx = ship.speedLimit;
}
if (ship.vx < -ship.speedLimit)
{
ship.vx = -ship.speedLimit;
}
if (ship.vy > ship.speedLimit)
{
ship.vy = ship.speedLimit;
}
if (ship.vy < -ship.speedLimit)
{
ship.vy = -ship.speedLimit;
}
//set stage boundaries
if (ship.x < 0)
{
ship.x = 0;
}
if (ship.y < 0)
{
ship.y = 0;
}
if (ship.x + ship.width > stage.stageWidth)
{
ship.x = stage.stageWidth - ship.width;
}
if (ship.y + ship.height > stage.stageHeight)
{
ship.y = stage.stageHeight - ship.height;
}
ship.x += ship.vx;
ship.y += ship.vy;
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
}
}
i recommend looking into tween utilities like TweenLite which do time based animations: (http://www.greensock.com/tweenlite/)
also recommend looking into object pooling, reused objects instead of creating new ones. Good thing to learn as a new programmer.
you are correct about where your issue lies
i got your program working correctly with the following change:
---------change these lines-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
}
if (starArray.indexOf(starArray.y) > stage.stageHeight) //if y property of any star is higher than stage height, create a new star
{
createStar();
}
---------to this-------------
//star enter frame code
for (var i:int = 0; i < numStars; i++)
{
var star:Star = starArray[i];
star.y += 0.5 + Math.random() * 2;
if (star.y>stage.stageHeight){
//dont create a new star -- memory leak
//move the same star to a new random location
star.y = 0;
}
}
Instead of just creating a new star, why not just replace it at the top outside of the screen?
As for indexOf, it only returns the index in an array of the object being passed. And in this case you're passing the y value of an array, which doesn't have that property.
Instead, move your position checking code to your for loop in the game loop. That way, you already have an index (your i variable) of the star that's outside the boundaries and if it is, just reposition it and save some memory!
for (var i:int = 0; i < numStars; i++)
{
starArray[i].y += 0.5 + Math.random() * 2;
if(starArray[i].y > stage.stageHeight)
{
// Repositions the star between x: 0 to stageWidth, y: -5 to -15
starArray[i].y = Math.random() * -10 - 5;
starArray[i].x = Math.random() * stage.stageWidth;
}
}
so I'm working on this simple game, in which you dodge falling boulders. Every time a boulder doesn't hit you (reaches a y coordinate below) you get 30 pts. And when a boulder does hit you you lose a life. Unfortunately, it seems to glitch out seemingly unpredictable.
LINK TO TEST OUT THE GAME: http://fozgamez.com/a
(only the 1p mouse works)
I do not know how to fix the problem, since I cannot figure out how/ when the problem happens.
My code for the 2nd scene (the one with the rules):
import flash.events.MouseEvent;
stop();
var livesSelected:Number;
m1Select.addEventListener(MouseEvent.MOUSE_UP, m1Selected)
function m1Selected (e:MouseEvent)
{
livesSelected = 01;
gotoAndStop(3);
}
m3Select.addEventListener(MouseEvent.MOUSE_UP, m3Selected)
function m3Selected (e:MouseEvent)
{
livesSelected = 03;
gotoAndStop(3);
}
m5Select.addEventListener(MouseEvent.MOUSE_UP, m5Selected)
function m5Selected (e:MouseEvent)
{
livesSelected = 05;
gotoAndStop(3);
}
m9Select.addEventListener(MouseEvent.MOUSE_UP, m9Selected)
function m9Selected (e:MouseEvent)
{
livesSelected = 09;
gotoAndStop(3);
}
CODE FOR THE 3RD SCENE (where you actually play the game):
import flash.events.Event;
import flash.events.TouchEvent;
import flash.events.MouseEvent;
import flash.utils.Timer;
var points:int = 0;
var lifeTimer:Timer = new Timer(1000, 1)
var lives:Number = livesSelected;
livesText.text = lives.toString();
pointsText.text = points.toString();
lifeTimer.stop()
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event){
mChar.x = mouseX;
mChar.y = mouseY;
b1.y += 20;
b2.y += 40;
b3.y += 15;
b4.y += 25;
b5.y += 20;
bFast.y += 50;
if(mChar.y <= 20)
{
mChar.y = 20;
}
if(mChar.x >= 700)
{
mChar.x = 700;
}
if(mChar.y <= 0)
{
mChar.y = 700;
}
if(b1.y >= 730) {
b1.y = (Math.random() + .001) * -200;
b1.x = (Math.random() + .001) * 700;
points += 15;
}
if(b2.y >= 730) {
b2.y = (Math.random() + .001) * -200;
b2.x = (Math.random() + .001) * 700;
points += 30;
}
if(b3.y >= 730) {
b3.y = (Math.random() + .001) * -200;
b3.x = (Math.random() + .001) * 700;
points += 15;
}
if(b4.y >= 730) {
b4.y = (Math.random() + .001) * -200;
b4.x = (Math.random() + .001) * 700;
points += 15;
}
if(b5.y >= 730) {
b5.y = (Math.random() + .001) * -200;
b5.x = (Math.random() + .001) * 700;
points += 15;
}
if(bFast.y >= 730) {
bFast.y = (Math.random() + .001) * -200;
bFast.x = (Math.random() + .001) * 700;
points += 15;
}
if(!lifeTimer.running) {
livesText.text = lives.toString();
mInvin.x = -66;
mInvin.y = 560;
pointsText.text = points.toString();
if(mChar.hitTestObject(b1)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b2)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b3)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b4)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(b5)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(mChar.hitTestObject(bFast)) {
lives--;
livesText.text = lives.toString();
lifeTimer.start();
}
if(lives <= 0)
{
gotoAndStop(7);
}
}
if(lifeTimer.running)
{
mInvin.x = mChar.x;
mInvin.y = mChar.y;
}
}
Thanks for reading: I know this is kind of a tough problem to figure out, so thanks for the help!
Your problem here, from what I can derive from your code, is your event listeners. I don't know what code you have on frame 7, but unless you remove the event listeners, they will keep on listening and running code, even though you have moved the playhead forward on the timeline (e.g. when calling gotoAndStop())
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);
}