Hey guys, i’m making a 2D game but i’have problem with my enemy shoot, when he instantiate a bullet, he instantiate many bullet but i would like one by one, this is the code of the enemy :
function OnTriggerStay(col : Collider) { if(col.gameObject.tag == "Player") { Instantiate(lazerBullet, shooter.transform.position, lazerBullet.transform.rotation); } }
and the code of the bullet :
//var perso : Transform;
var shootSpeed : int;
function Start ()
{
}
function Update ()
{
var shoot = Time.deltaTime * shootSpeed;
transform.Translate(0,-shoot,0);
}
Perhaps try this?
var shootSpeed : int;
// Set in Editor to be how many shots are fired per second
var shotsPerSecond : float;
private var shotTimer : float;
private var shotTimerElapsed : float;
function Start ()
{
shotTimer = 1 / shotsPerSecond;
shotTimerElapsed = 0;
}
function Update ()
{
shotTimerElapsed = shotTimerElapsed + Time.deltaTime;
}
function OnTriggerStay(col : Collider)
{
if (col.gameObject.tag == "Player") {
if (shotTimerElapsed >= shotTimer)
{
shotTimerElapsed = 0;
Instantiate(lazerBullet, shooter.transform.position, lazerBullet.transform.rotation);
}
}
}
You don’t really want to be increasing a timer in a collision or trigger event since it can happen multiple times in the same frame depending on how many things are colliding in that frame.
OnTriggerStay will repeatedly activate as long as the collider is touching. You could add in a delay, such as:
var delay = 0.0;
var delayAmount = 1.0;
function OnTriggerStay(col : Collider)
{
if (col.gameObject.tag == "Player" && Time.time > delay)
{
delay = Time.time + delayAmount;
Instantiate(lazerBullet, shooter.transform.position, lazerBullet.transform.rotation);
}
}
That way, you’ll force it to wait (in this case) a second before firing again.
it WORK’s, thank you so much dude and sorry if my english is not well, i’m French lol