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);
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.