Zoske
Zoske

Reputation: 39

AS3 - Score when hitTestObject

In this game I made some cubes fall and you have to avoid them. When you've avoided one, it keeps falling and hits the ground (scoreDetector), so everytime it hits the ground, I get 1 point. The problem is that the animatione of the cube keeps looping (that's what I want) but by doing so the score counter removes the point and keeps adding and removing it everytime the animation of the cube starts.

Code:

var time:int;
var timer:Timer = new Timer(1000,0);
var score:int = 0;

score = 0;
scoreCounter.text = "Score:  " + score;

timer.addEventListener(TimerEvent.TIMER, cubeFall);

timer.start();

function cubeFall(t:TimerEvent) {

time++;

if (time == 3) {
    cube_1.play();
} else if (time == 10) {
    cube_2.play();
}

// Add Score

else if (cube_1.hitTestObject(scoreDetector)) {
score++;
scoreCounter.text = "Score:  " + score;
}
}

Upvotes: 0

Views: 4713

Answers (2)

Syed
Syed

Reputation: 79

That's one solution Khaled, nice thinking! :) but It is not a matter of arrays. The hitTest should not be in an else if() statement. It should be in it's own if() statement. Secondly, score++; should be the only thing inside the hitTest if() statement. The scoreCounter.text = "Score: " + score; should be outside the if() statement. Here is what it should look like.

var time:int;
var timer:Timer = new Timer(1000,0);
var score:int = 0;

score = 0;
scoreCounter.text = "Score:  " + score;

timer.addEventListener(TimerEvent.TIMER, cubeFall);

timer.start();

function cubeFall(t:TimerEvent) {

time++;

if (time == 3) {
    cube_1.play();
} else if (time == 10) {
    cube_2.play();
}

// Add Score

if (cube_1.hitTestObject(scoreDetector)) {
score++;
}
scoreCounter.text = "Score:  " + score;
}

Upvotes: 0

Khaled Garbaya
Khaled Garbaya

Reputation: 1497

Hi you can use an array that will contain the hitted elements like so :

var time:int;
var timer:Timer = new Timer(1000,0);
var score:int = 0;
var hittedObjects:Array = new Array();
score = 0;
scoreCounter.text = "Score:  " + score;

timer.addEventListener(TimerEvent.TIMER, cubeFall);

timer.start();

function cubeFall(t:TimerEvent) {

time++;

if (time == 3) {
    cube_1.play();
} else if (time == 10) {
    cube_2.play();
}

// Add Score

else if (cube_1.hitTestObject(scoreDetector) && hittedObjects.indexOf(cube_1)>0) {
score++;
scoreCounter.text = "Score:  " + score;
hittedObjects.push(cube_1);
}
}

Upvotes: 1

Related Questions