I have a simple system where when i release the mouse button i spawn in an arrow and it shoots forward (or to the raycast hit point).
Now i want to add in a system where the power (or speed) of the arrow is increased depending on how long you hold the mouse button up to a certain value. In a similar way to games such as Skyrim.
My guess is that i need to have a base power that is multiplied by a value that increases over time when the button is held down.
I have tried a bunch of things and nothing i can do works as i am still fairly new to coding.
Here is the script i’m using to fire the arrow:
public Rigidbody arrow ;
public float power = 1500f ;
public int maxAmmo = 100;
public int currentAmmo;
void Start ()
{
currentAmmo = maxAmmo;
}
void Update ()
{
if (currentAmmo > 0) {
if (Input.GetButtonUp ("Fire1"))
{
Rigidbody instance = Instantiate (arrow, transform.position,
transform.rotation) as Rigidbody;
Vector3 fwd = transform.TransformDirection (Vector3.forward);
instance.AddForce (fwd * power);
currentAmmo--;
Debug.Log (currentAmmo);
}
}
}
}
Something like this? I changed the ‘FireButton’ in the script to Keyboard J just for testing. Change it to whatever you like.
float barrelClearance = 2.0f;
float chargeTimer = 0.0f;
float chargeTimeMax = 5.0f;
//int currentAmmo = 10; //DUMMY
void Update ()
{
if (currentAmmo > 0)
{
if(Input.GetKey(KeyCode.J))
{
chargeTimer += Time.deltaTime;
if (chargeTimer >= chargeTimeMax)
{
Fire(chargeTimeMax);
chargeTimer = 0.0f;
}
}
else if (Input.GetKeyUp (KeyCode.J))
{
Fire(chargeTimer);
chargeTimer = 0.0f;
}
}
}
//public Rigidbody arrow; //DUMMY
//float power = 100.0f; //DUMMY
void Fire(float scaler)
{
Vector3 transPosAdjust = new Vector3(0.0f, 0.0f, barrelClearance); //(transform.position.x, transform.position.y, transform.position.z + barrelClearance);
Rigidbody instance = Instantiate (arrow, transform.TransformPoint(transPosAdjust), transform.rotation) as Rigidbody;
instance.AddRelativeForce(new Vector3(0.0f,0.0f, power * scaler), ForceMode.Impulse);//(fwd * power * scaler);
currentAmmo--;
Debug.Log (power * scaler);
}
}
It should go like this : Pressing and holding the button begins a timer. If you exceed max, it fires and sets the ‘scaler’ to max. If you let go before max it Fires and the scaler is equal to charge timer. You can scale this however you wish, its just for illustration.