Checking current animation sprite

Im trying to make a power bar for a 2D cannonball launcher. I have an animation that cycles through 7 sprites. In my script, I want to check the current sprite in the animation upon mouse click. Depending on what frame the power bar is on, I want the cannon to shoot at a specific force. The code I have tracks the mouse movement, and shoots towards its click location.

if (Input.GetMouseButtonDown(0)){

     var pos = Input.mousePosition;
         pos.z = transform.position.z - Camera.main.transform.position.z;
         pos = Camera.main.ScreenToWorldPoint(pos);

         var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
         var go = Instantiate(newCB, transform.position, q);

        //check current sprite, assign power here
         go.rigidbody2D.AddForce(go.transform.up * 1000.0);

Hello,
I’ve done this a different way, and it works for me :

  • Create a gameobject called Powerbar which is a sprite with an animation
    of 7 different sprite on it.

create a script for it with in it a function like this one

void setPower(float val){
		Debug.Log( val);
           //next I pass the val throught a gameobject present on the main stage
		}
  • On the animation window,at each
    changes of sprite you create an event
    (the little icon “Add Event” near the
    number of frames next to the play
    button)
  • The event asks you to choose a function (setpower(float val)), and
    the number of the val to pass
  • In each different frame set the wanted power.

and it’s done, like this you get the val of the current animation step each time you check this value

As far as detecting the frame a sprite animation is on, try this:

// Get the state info from the animator controlling your sprite animation
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
// normalizedTime is a value from 0.0 to 1.0 for the length through the animation.
float animationPercent = (stateInfo.normalizedTime % 1.0f);
// Here we get the current frame using the animationPercent
int currentFrame = Mathf.FloorToInt(animationPercent * 7.0f)+1;

Now you have an int to represent what frame the animation is on.

Although if I may make a suggestion, I would recommend having a value in your script detect how long the mouse has been held down and use that to govern what frame to display, and what power to shoot your projectile with. Let your script control the power and the animation. Not the animation control the power. That is, unless you need 7 distinct values corresponding to each frame. If not, this method will allow for more varied launch powers. Cheers.