问题
I am creating a game using AS3. I need to display the final score for the player on the next key frame when the game is over. When the player collides with an enemy the players score increments by 1.
This is the code I have which updates the score.
var playerScore:int = 0;
function updateTextFields():void
{
playerScoreText.text = ("Score: " + playerScore);
}
function caught(enemy:MovieClip):void
{
enemy.removeEventListener(Event.ENTER_FRAME,dropEnemy);
removeChild(enemy);
playerScore++;
updateTextFields();
}
I need to show the final score for the player on the game over screen but because the value for playerScore is dynamic and increments by one I can't just display
playerScoreText.text = ("Score: " + playerScore);
as the variable default is 0.
I have tried but I can't figure out how to make it work.
var playerScore = playerScore;
回答1:
If you want to use var in every frame you have to put it into a class (before the Main function). Also you should use public or private prefix. If you add private you ca use this variable only in this class, and public will enable you to use it in every class that is related to that file.Also it's good idea to use uint instead of int.
For example it should look like that:
package
{
//import...
public class Main extends //(you should write Sprite, MovieClip... there)
{
public var playerScore:uint = 0;
public function Main()
{
//constructor
}
}
}
回答2:
If you get rid of the = 0 then it should work. playerScore is being set to 0 by the frame script. If all you have is the declaration var playerScore:int;, the variable will default to zero and Flash won't add the statement playerScore = 0 to the frame script (a function that's called every time the particular frame is reached).
In general, it's better to declare a class explicitly. The way Flash generates a class from scripts added to frames can be rather confusing, as a single statement can end up in two places. For instance, your above code will actually become the following:
package filename_fla
{
public dynamic class MainTimeLine extends MovieClip
{
public var playerScore:int;
internal function frame1:*
{
playerScore = 0;
}
public function updateTextFields():void
{
playerScoreText.text = ("Score: " + playerScore);
}
public function caught(enemy:MovieClip):void
{
enemy.removeEventListener(Event.ENTER_FRAME,dropEnemy);
removeChild(enemy);
playerScore++;
updateTextFields();
}
}
}
来源:https://stackoverflow.com/questions/12252688/display-dynamic-variable-on-next-key-frame-as3