- Home /
Trouble with Raycast shooting
When i shoot at a target it is mean to take 5 hits to make it disappear, but in stead its disappearing and all 5 notifications are appearing at once in the console and the target is destroyed immediately.
Gun code
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
// Update is called once per frame
void Update ()
{
if (Input.GetButton ("Fire1"))
{
Shoot ();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast (fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log (hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
}
}
target code
public float health = 50f;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die ()
{
Destroy(gameObject);
Debug.Log ("object destroyed");
}
Any suggestions as to why?
Answer by Legend_Bacon · Oct 30, 2018 at 06:03 PM
Hello there,
You are using Input.GetButton() in Update, which means it will return true each frame as long as the button is pressed.
You have two solutions here:
• Either you want to shoot as long as the button is pressed, in which case you would need to implement a cooldown
• Or you want to shoot once with every button press, in which case you can just replace that line with Input.GetButtonDown() or Input.GetButtonUp(). This only return true in the one frame when it goes from one state to the other.
I hope that helps!
Cheers,
~LegendBacon
Your answer
Follow this Question
Related Questions
Raycast shooting in the middle of the screen 1 Answer
Raycast shooting 1 Answer
scripting problem 0 Answers
How do I make my raycast shooting script full auto 1 Answer
Shotgun raycast 1 Answer