My game counts the number of hits to an object and brings the user either to a winning or losing page. How can my hitTestObject count the number of hits while showing the number on the main stage? If the user hits "friend" 5 times, I want it to play the "youWin" layer and if they hit a "biter" once, I want it to play the "youLose" layer. (Please help this is for my final project and I'm almost done) Thank you! :)
stop();
addEventListener(Event.ENTER_FRAME,fishHit);
function fishHit(e:Event){
if (theFish.hitTestObject(biter)){
removeEventListener(Event.ENTER_FRAME,fishHit);
gotoAndPlay("youLose");
}
}
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter:shark=new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
}
for (var what=0; what<5; what++){
var friend:starfish=new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
}
var counter : int = 0;
addEventListener(Event.ENTER_FRAME,winner);
function winner (e:Event){
if(theFish.hitTestObject(friend)) {
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5)
removeEventListener(Event.ENTER_FRAME,winner);
gotoAndPlay("youWin");
}
}
You need many updates in your code, but I'll try to copy and paste your code with small modifications. You should define your variables outside of for loop, also you must add multiple objects like 'friends' to an array.
stop();
// arrays
var friends:Array = new Array();
var biters:Array = new Array();
var counter : int = 0;
var theFish:fish = new fish();
theFish.x = 200
theFish.y = 260
addChild(theFish);
for (var which=0; which<5; which++){
var biter = new shark();
biter.x=1400;
biter.y=int(Math.random()*660.0+30.0);
addChild(biter);
// push it to the array
biters.push(biter)
}
for (var what=0; what<5; what++){
var friend = new starfish();
friend.x=1400;
friend.y=int(Math.random()*660.0+30.0);
addChild(friend);
// push it to the array
friends.push(friend)
}
addEventListener(Event.ENTER_FRAME, enterFrame);
function enterFrame(e:Event){
// theFish vs biters
for (var i:int = 0; i < biters.length; i++){
if (theFish.hitTestObject(biters[i])){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youLose");
}
}
// theFish and friends
for (i = 0; i < friends.length; i++){
if(theFish.hitTestObject(friends[i])) {
// remove this friend so it does not increase counter
friends.splice(i,1);
counter += 1
scoreboard.score_text.text = counter;
if(counter == 5){
removeEventListener(Event.ENTER_FRAME, enterFrame);
gotoAndPlay("youWin");
}
}
}
}