- Home /
I need help calculating player shot accuracy!
Hello everyone! I was just making a small tank game and I wanted the game to calculate the player's shooting accuracy, so I coded this script -
var tanks = 1; private var tanksShot = 0;
function Start () {
tanksShot = tanks;
}
function Update () {
if(tanks==0)
{
completed = true;
}
}
private var completed = false;
function OnGUI () {
if(completed)
{
var hitPercent : float = tanksShot/Shoot.shots;
var accuracy : int = hitPercent*100;
var newPionts = tanksShot+accuracy;
GUI.Box(Rect(Screen.width/2-150,Screen.height/2-150,300,300),"Level Completed");
GUI.Label(Rect(Screen.width/2-150+20,Screen.height/2-150+20,200,30),"Tanks destroyed: "+tanksShot);
GUI.Label(Rect(Screen.width/2-150+20,Screen.height/2-150+50,200,30),"Shots taken: "+Shoot.shots);
GUI.Label(Rect(Screen.width/2-150+20,Screen.height/2-150+80,200,30),"Shot accuracy: "+accuracy+"%/100%");
GUI.Label(Rect(Screen.width/2-150+20,Screen.height/2-150+110,200,30),"Pionts awarded: "+newPionts);
if(GUI.Button(Rect(Screen.width/2-150+20,Screen.height/2-150+170,120,30),"Main menu"))
{
Application.LoadLevel(0);
Shoot.shots = 0;
Shoot.canShoot = true;
HealthScript.LIVES = 3;
}
if(GUI.Button(Rect(Screen.width/2-150+160,Screen.height/2-150+170,120,30),"Continue"))
{
Application.LoadLevel(Application.loadedLevel+1);
//reset everthing!
completed = false;
Shoot.shots = 0;
Shoot.canShoot = true;
HealthScript.LIVES = 3;
}
}
}
expecting it to work, but NO! For example if a player shoots 2 times, or more, to destroy one tank it will say 0&/100&, wich is really weird, so does anyone know why it's saying that?
Answer by Bunny83 · May 03, 2011 at 01:18 AM
Well, the problem is that if you divide an int by an int the result will be an int. You assign the result to a float variable but the calculation itself is an integer division that get truncated... 1/2 = 0.5 => 0
You have to use float variables to cast the ints into floats. In C# it's a bit simpler but in JS you have to use temp variables:
var tanksShot_F : float = tanksShot;
var shots_F : float = Shoot.shots;
var hitPercent : float = tanksShot_F/shots_F;
var accuracy : int = hitPercent*100.0;
I also changed the 100 (integer) into 100.0 (float) to be on the safe side. float * int will result in a float but it's easier to read.
Your answer
Follow this Question
Related Questions
Simple Maths Problem (I Suck At Maths) 2 Answers
how can i know a percent of animation ?? 1 Answer
Progression height affected by the width ? why 1 Answer
Percentage for random 1 Answer