How do i remove the milliseconds from my timer - timer

I am making this game for school and I am trying to add a timer to levels. I have the timer working but not the way I want it to. It refreshes and it has milliseconds. I have searched every website for an answer but I can only find with dates and times or how do display them. I need the exact opposite.
package GameState;
import Main.GamePanel;
import TileMap.*;
import Entity.*;
import Entity.Enemies.*;
import Audio.AudioPlayer;
//timer imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Level1State extends GameState {
private TileMap tileMap;
private Background bg;
private static int cnt;
private Player player;
private ArrayList<Enemy> enemies;
private ArrayList<Explosion> explosions;
private HUD hud;
private AudioPlayer bgMusic;
public Level1State(GameStateManager gsm) {
this.gsm = gsm;
init();
}
public void init() {
tileMap = new TileMap(30);
tileMap.loadTiles("/Tilesets/grasstileset.gif");
tileMap.loadMap("/Maps/level1-1.map");
tileMap.setPosition(0, 0);
tileMap.setTween(1);
bg = new Background("/Backgrounds/grassbg1.2.jpg", 0.1);
player = new Player(tileMap);
player.setPosition(100, 100);
populateEnemies();
explosions = new ArrayList<Explosion>();
hud = new HUD(player);
bgMusic = new AudioPlayer("/Music/level1-1.mp3");
bgMusic.play();
}
private void populateEnemies() {
enemies = new ArrayList<Enemy>();
Slugger s;
Point[] points = new Point[] {
new Point(200, 100),
new Point(860, 200),
new Point(1525, 200),
new Point(1680, 200),
new Point(1800, 200)
};
for(int i = 0; i < points.length; i++) {
s = new Slugger(tileMap);
s.setPosition(points[i].x, points[i].y);
enemies.add(s);
}
}
public void update() {
// update player
player.update();
tileMap.setPosition(
GamePanel.WIDTH / 2 - player.getx(),
GamePanel.HEIGHT / 2 - player.gety()
);
// set background
bg.setPosition(tileMap.getx(), tileMap.gety());
// attack enemies
player.checkAttack(enemies);
// update all enemies
for(int i = 0; i < enemies.size(); i++) {
Enemy e = enemies.get(i);
e.update();
if(e.isDead()) {
enemies.remove(i);
i--;
explosions.add(
new Explosion(e.getx(), e.gety()));
}
}
// update explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).update();
if(explosions.get(i).shouldRemove()) {
explosions.remove(i);
i--;
}
}
}
public void draw(final Graphics2D g) {
// draw bg
bg.draw(g);
// draw tilemap
tileMap.draw(g);
// draw player
player.draw(g);
// draw enemies
for(int i = 0; i < enemies.size(); i++) {
enemies.get(i).draw(g);
}
// draw explosions
for(int i = 0; i < explosions.size(); i++) {
explosions.get(i).setMapPosition(
(int)tileMap.getx(), (int)tileMap.gety());
explosions.get(i).draw(g);
}
// draw hud
hud.draw(g);
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
}
public void keyPressed(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(true);
if(k == KeyEvent.VK_RIGHT) player.setRight(true);
if(k == KeyEvent.VK_UP) player.setUp(true);
if(k == KeyEvent.VK_DOWN) player.setDown(true);
if(k == KeyEvent.VK_W) player.setJumping(true);
if(k == KeyEvent.VK_E) player.setGliding(true);
if(k == KeyEvent.VK_R) player.setScratching();
if(k == KeyEvent.VK_F) player.setFiring();
}
public void keyReleased(int k) {
if(k == KeyEvent.VK_LEFT) player.setLeft(false);
if(k == KeyEvent.VK_RIGHT) player.setRight(false);
if(k == KeyEvent.VK_UP) player.setUp(false);
if(k == KeyEvent.VK_DOWN) player.setDown(false);
if(k == KeyEvent.VK_W) player.setJumping(false);
if(k == KeyEvent.VK_E) player.setGliding(false);
}
}
this is the part i need help with:
ActionListener actListner = new ActionListener() {
public void actionPerformed(ActionEvent event) {
cnt += 1;
g.drawString("Counter = "+cnt, 120, 120);
}
};
Timer timer = new Timer(1000, actListner);
timer.start();
Can anyone help me? I just can't get it to stop refreshing and it won't remove the milliseconds either.
Thank you in advance
P.S.
I have a feeling the first second runs way slower than the others.
P.P.S.: i have looked at "how to implement timers" but none of those worked and I found this one on a website that doesn't return an error.

Related

WPF list modification during iteration?

I'm trying to make a very simple game where the yellow ball bouncing back and fourth. If it collides with one of the moving blue squares, the square is supposed to disappear and a new one should appear (always 3 in the window) elsewhere. When my code reaches this part, all 3 squares disappear (then reappears as intended it is not a problem) and I just cant figure out why. It would be a huge help if somebody could run over my methods responsible for the problem. Thank you in advance.
So my timer_Tick method, responsible for every frame:
void timer_Tick(object sender, EventArgs e)
{
logic.MoveBall();
if (model.Enemy.Count<3)
{
logic.AddEnemy();
}
int iii = 0;
foreach (MyShape enemy in model.Enemy) //the whole thing from here is me trying to solve list modification during iteration
{
if (logic.MoveEnemy(enemy) == -1)
{
logic.MoveEnemy(enemy);
}
else iii = logic.MoveEnemy(enemy);
}
if (iii > -1)
{
for (int j = model.Enemy.Count - 1; j >= 0; j--)
{
if (j == model.Enemy.Count - iii)
{
model.Enemy.RemoveAt(j);
}
}
}
}
MoveEnemy: I try to decide whether there is collusion and if yes, then try to remove the given shape object (blue square). Because This whole method is in a foreach, I just save the removable element and forward it to timer_Tick
public int MoveEnemy(MyShape shape)
{
int i = 0;
int ii = -1;
if ((shape.Area.IntersectsWith(model.Ball.Area)))
{
i = 0;
foreach (var e in model.Enemy)
{
i++;
if (shape == e)
{
ii = i;
}
}
}
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool coll = false;
foreach (var e in model.Enemy)
{
if ((e.Area.IntersectsWith(shape.Area)) && (shape != e))
{
coll = true;
}
}
if (shape.Area.Left < 0 || shape.Area.Right > Config.Width-40 || coll)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height/2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
return ii;
}
And finally AddEnemy:
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2+r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
List<T> (or IList and Enumerable) exposes some useful methods to compact code:
int itemIndex = list.IndexOf(item); // Gets the index of the item if found, otherwise returns -1
list.Remove(item); // Remove item if contained in collection
list.RemoveAll(item => item > 5); // Removes all items that satisfy a condition (replaces explicit iteration)
bool hasAnyMatch = list.Any(item => item > 5); // Returns true as soon as the first item satisfies the condition (replaces explicit iteration)
A simplified version, which should eliminate the flaw:
void timer_Tick(object sender, EventArgs e)
{
if (model.Enemy.Count < 3)
{
logic.AddEnemy();
}
logic.MoveBall();
model.Enemy.ForeEach(logic.MoveEnemy);
model.Enemy.RemoveAll(logic.IsCollidingWithBall);
}
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2 + r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
public bool IsCollidingWithBall(MyShape shape)
{
return shape.Area.IntersectsWith(model.Ball.Area);
}
public int MoveEnemy(MyShape shape)
{
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool hasCollision = model.Enemy.Any(enemy => enemy.Area.IntersectsWith(shape.Area)
&& enemy != shape);
if (hasCollision || shape.Area.Left < 0 || shape.Area.Right > Config.Width - 40)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height / 2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
}

Combining two instantiate scripts (Unity 3D)

I need to combine the following scripts into one script containing two functions, one that instantiates the next prefab in the array and the other that instantiates the previous prefab in the array (it is a virtual tour app). Both should also destroy the current prefab. I could then call the functions via event triggers.
I have this code for the "next Prefab" script.
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowNEXT")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
I need to combine it with the following:
using UnityEngine;
public class RayCastPrevFIX: MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
if (gameObject.tag == "ArrowPREV")
{
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
}
}
}
How would I go about this? Any help is greatly appreciated.I have this so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
void Next()
{
Destroy(currentObject);
currentIndex++;
if (currentIndex > Spheres.Length - 1) currentIndex = 0;
currentObject = Instantiate(Spheres[currentIndex]);
}
void Previous()
{
Destroy(currentObject);
currentIndex--;
if (currentIndex < 0) currentIndex = Spheres.Length - 1;
currentObject = Instantiate(Spheres[currentIndex]);
}
}
You're on the right path, but you could shorten the code as well as use one function for both cases to avoid boilerplate:
using UnityEngine;
public class SphereSwap : MonoBehaviour
{
public GameObject[] Spheres;
int currentIndex = 0;
GameObject currentObject;
public Camera MainCamera;
const string ArrowPrevTag = "ArrowPREV";
const string ArrowNextTag = "ArrowNEXT";
private void HandleClick(bool next)
{
if(Spheres == null || Spheres.Length == 0)
{
Debug.Log($"Spheres list is empty, nothing to swap.");
return;
}
Vector3 rayOrigin = MainCamera.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0));
RaycastHit hit;
if (Physics.Raycast(rayOrigin, MainCamera.transform.forward, out hit))
{
if (hit.collider != null)
{
// destroy current sphere.
Destroy(currentObject);
// go next or previous.
currentIndex += next ? 1 : -1;
// circular clamp if overflow
if (currentIndex < 0)
currentIndex = Spheres.Length - 1;
else if (currentIndex >= Spheres.Length)
currentIndex = 0;
// finally do instantiate.
currentObject = Instantiate(Spheres[currentIndex]);
}
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
// 'CompareTag' is more efficient than gameobject.tag == "sometag"
if (gameObject.CompareTag(ArrowNextTag))
HandleClick(true);
else if (gameObject.CompareTag(ArrowPrevTag))
HandleClick(false);
}
}
}

How to let Stage show the pictures after timer

After I click start button, my program will not show the second scene and thread , until the thread is finish. And the thread will not run correctly(grass didn't increase).
public class test111 extends Application {
private static int grass_i=130;
private static int grass_j=200;
private static int[][] map = new int[grass_i][grass_j];//草地資料grassdata
private static int totalgrass; //grass total number
private static int totalgrassrest; //grass rest number
private static int months=1; //月
private Timer timer;//時間
//GUI
Scene menusc ;
//START後的視窗
BorderPane bpAll = new BorderPane();
Pane playView = new Pane();
Scene mainsc = new Scene(bpAll);
//草
Image littlegrassImg = new Image(getClass().getResourceAsStream("map_littlegrass.png"));
Image midiumgrassImg = new Image(getClass().getResourceAsStream("map_midiumgrass.png"));
Image muchgrassImg = new Image(getClass().getResourceAsStream("map_muchgrass.png"));
Rectangle2D[][] viewportRect = new Rectangle2D[130][200];
private static ImageView[][] mapView = new ImageView[130][200];
//時間
#Override
public void start(Stage primaryStage) throws InterruptedException {
//MENU
Pane menu = new Pane();
menusc = new Scene(menu);
menu.setPrefSize(1000, 800);
Image MenuImg = new Image(getClass().getResourceAsStream("Menu_title.jpg"));
Image StartImg = new Image(getClass().getResourceAsStream("Start.jpg"));
menu.getChildren().add(new ImageView(MenuImg));
Button StartBt = new Button();
StartBt.setPrefSize(450, 150);
StartBt.setGraphic(new ImageView(StartImg));
StartBt.setMaxSize(450, 150);
StartBt.setLayoutX(300);
StartBt.setLayoutY(600);
menu.getChildren().addAll(new ImageView(MenuImg),StartBt);
primaryStage.setMinHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMinWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setMaxHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMaxWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setScene(menusc);
primaryStage.setTitle("Hypnos' yard");
//START
StartBt.setOnAction(e->{
BorderPane bp2 = bp2();
menusc = new Scene(bp2);
primaryStage.setScene(menusc);
});
primaryStage.show();
}
public BorderPane bp2(){
playView = playView();
bpAll = new BorderPane();
bpAll.setPrefSize(1000, 800);
playView.setPrefSize(1000, 650); //庭院
bpAll.setTop(playView);
Random ran = new Random();
totalgrass = (ran.nextInt(50)*1000)+48000;
totalgrassrest = totalgrass;
grasscreate();
//設定初始草地construct the initial grass
grassGraphicsLoading(); //loading grass pictures
return bpAll;
}
public Pane playView(){
playView = new Pane();
while(months<12){
timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
month();
}
};//after program executing 0.2s, a month past
timer.schedule(task, 200);
try {
Thread.sleep(200);
}
catch(InterruptedException e6) {
}
timer.cancel();
}
return playView;
}
//月month
protected void month(){
if(months<13){
grassgrow(totalgrass*2);//grass growth
Platform.runLater(new Runnable(){
#Override
public void run(){
grassGraphicsLoading();
}
});
months++;
}
}
//把草地資料帶入圖形loading grass pictures
private void grassGraphicsLoading(){
for (int i = 0; i < grass_i; i++) { // 設定imageView的圖形和位置
for (int j = 0; j < grass_j; j++) {
viewportRect[i][j] = new Rectangle2D(j * 5, i * 5, 5, 5);
if (170 <= j && j <= grass_j - 1) {
mapView[i][j] = new ImageView(muchgrassImg);
} else if (140 <= j && j < 170) {
mapView[i][j] = new ImageView(muchgrassImg);
} else {
if (map[i][j] == 0) {
mapView[i][j] = new ImageView(littlegrassImg);
} else if (map[i][j] == 1 || map[i][j] == 2) {
mapView[i][j] = new ImageView(midiumgrassImg);
} else {
mapView[i][j] = new ImageView(muchgrassImg);
}
}
playView.getChildren().add(mapView[i][j]);
mapView[i][j].setViewport(viewportRect[i][j]);
mapView[i][j].setX(j * 5);
mapView[i][j].setY(i * 5);
}
}
}
public static void main(String[] args) {
launch(args);
}
// 每經過30天(一個月)草地+1grassgrowth
protected void grassgrow(int sum) {
for (int i = 0; i < grass_i; i++) {
for (int j = grass_j - 1; j >= 0; j--) {
if (map[i][j] < 4 && totalgrass <sum) {
map[i][j] += 1;
totalgrass++;
}
if (totalgrass == 104000||totalgrass ==sum) {
break;
}
}
}
}
//建構草地construct grass
protected void grasscreate() {
for (int j = grass_j - 1; j >= 0; j--) {
for (int i = grass_i - 1; i >= 0; i--) {
if (170 <= j && j <= grass_j - 1) {
map[i][j] = 0;
} else if (140 <= j && j < 170) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest <= 0) {
map[i][j] = 0;
} else if (4 * (j + 1) * grass_i <= totalgrassrest) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest < 4) {
map[i][j] = totalgrassrest;
totalgrassrest = 0;
} else {
map[i][j] = rancreate();
totalgrassrest -= map[i][j];
}
}
}
totalgrass -= totalgrassrest;
totalgrassrest = 0;
}
// 一格(5X5)內草地數量隨機1-4平米z there is 1-4 grass inside a rectangle
private int rancreate() {
Random ran = new Random();
int grass = ran.nextInt(5);
return grass;
}
}`

How to create multiple instances of the same class in as3?

Noob question. Ok, so I'm trying to create two instances of my notes (it's an imported pic) class at separate x and y coordinates, then I want both of them to move right. Right now I programmed a loop, and the loop works OK, but it only keeps the last instance that was created. Here's my code. I really appreciate any help that anyone can give. Thanks!
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.utils.getDefinitionByName;
[Frame(factoryClass="Preloader")]
public class Main extends Sprite
{
private var speed:int = 8;
[Embed(source="../lib/Dodgethis.jpg")]
public var Notes:Class;
public var numnotes:Number;
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
stage.addEventListener(KeyboardEvent.KEY_DOWN, testevent);
}
private function testevent(e:Event = null):void {
trace("testevent has run");
appear(350, 250);
//ap2(150, 150)
//addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function appear(x:Number, y:Number) {
var arr1:Array = new Array;
numnotes = 4;
for (var i = 0; i < numnotes; i++)
{
trace (i);
var nbm:Bitmap = new Notes;
if (i == 0) {
this.x = 400;
this.y = 400;
addChild(nbm);
trace ("1 should be different");
} else {
trace ("this is working");
this.x = 150;
this.y = 150;
addChild(nbm);
arr1.push(nbm);
You have created 4 Notes, but their positions are same point (0,0).

AS3 - Array Object still being updated?

So in my game I'm using an array of enemies for keeping track of them and updating them and so on - when the player crashes into a enemy its game however, however if the player shoots a bullet that hits the enemy the enemy is deleted. Well thats supposed to be what happens however when the bullet its the enemy it deletes it but for some reason that object is still being updated and can still crash into the player?
How do I go about stopping this?
This is the code that I have in the laser class for checking for collisions
private function loop(e:Event) : void
{
//move bullet up
y -= bulletSpeed;
if (y < 0)
{
removeSelf();
}
for (var i:int = 0; i < AvoiderGame.enemyArray.length; i++)
{
if (hitTestObject(AvoiderGame.enemyArray[i]))
{
AvoiderGame.enemyArray[i].takeHit();
removeSelf();
}
}
}
This is all the code that I have in the enemy class.
package
{
import flash.display.MovieClip;
import flash.display.Stage;
public class Enemy extends MovieClip
{
private var stageRef:Stage;
public function Enemy(startX:Number, startY:Number, stageRef:Stage)
{
this.stageRef = stageRef;
x = startX;
y = startY;
}
public function moveDown():void
{
y = y + (1 + (10 - 1) * Math.random());
switch(Math.round(1 + (2 - 1) * Math.random()))
{
case 1: x = x + (1 + (10 - 1) * Math.random());
break;
case 2: x = x - (1 + (10 - 1) * Math.random());
break;
};
}
public function StayOnScreen():void
{
if (x <= 0)
{
x = 0;
}
else if (x >= stageRef.stageWidth)
{
x = stageRef.stageWidth;
}
else
{
x = x;
}
}
private function removeSelf() : void
{
if (stageRef.contains(this))
{
this.parent.removeChild(this);
delete AvoiderGame.enemyArray[this];
}
}
public function takeHit() : void
{
removeSelf();
}
}
}
This is all the code that I have in the main game.
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.freeactionscript.CollisionTest;
import flash.display.Stage;
import flashx.textLayout.formats.BackgroundColor;
public class AvoiderGame extends MovieClip
{
public static var enemyArray:Array;
public var enemy:Enemy
public var Background:gameBackground;
public var avatar:Avatar;
public var gameTimer:Timer;
private var _collisionTest:CollisionTest;
private var numStars:int = 80;
private var fireTimer:Timer; //causes delay between fires
private var canFire:Boolean = true; //can you fire a laser
public function AvoiderGame()
{
Background = new gameBackground();
addChild(Background);
enemyArray = new Array();
var enemy = new Enemy(Math.round(1 + (500 - 1) * Math.random()), - 2, stage);
enemyArray.push(enemy);
addChild(enemy);
avatar = new Avatar(stage);
addChild(avatar);
avatar.x = stage.stageWidth / 2;
avatar.y = stage.stageHeight / 2;
for (var i:int = 0; i < numStars; i++)
{
stage.addChildAt(new Star(stage), 1);
}
_collisionTest = new CollisionTest();
gameTimer = new Timer(25);
gameTimer.addEventListener(TimerEvent.TIMER, onTick);
gameTimer.start();
fireTimer = new Timer(300, 1);
fireTimer.addEventListener(TimerEvent.TIMER, fireTimerHandler, false, 0, true);
fireTimer.start();
}
public function onTick(timerEvent:TimerEvent):void
{
if (Math.random() < 0.1)
{
var enemy = new Enemy(Math.round(1 + (500 - 1) * Math.random()), - 28, stage);
enemyArray.push(enemy);
addChild(enemy);
}
avatar.UpdateAvatar(canFire);
if (canFire == true)
{
canFire = false;
fireTimer.start();
}
avatar.StayOnScreen();
for each (var enemy:Enemy in enemyArray)
{
enemy.moveDown();
enemy.StayOnScreen();
if (_collisionTest.complex(enemy, avatar))
{
gameTimer.stop();
}
}
}
private function fireTimerHandler(e:TimerEvent) : void
{
//timer ran, we can fire again.
canFire = true;
}
}
I understand that im probably going wrong in the enemy class with the removeSelf() function but how would i go about fixing this?
If you dont get want I mean - there is a playable example of this game on my website using space to shot will destroy the enemy but it will still be in the game?
http://dynamite-andy.co.uk/projects/free-time/as3-avoider-game/
The problem seems to be with this line in the removeSelf() method:
delete AvoiderGame.enemyArray[this];
To delete something from an Array you have to use one the Array class methods that modifies the array rather than the delete keyword.
[EDIT]
In this case, you can use splice(), to remove the enemy from the array:
var enemyIndex:int = this.parent.getChildIndex(this);
this.parent.removeChild(this);
AvoiderGame.enemyArray.splice(enemyIndex, 1);

Resources