Hey guys,
I cant make my enemy shoot with delay and to do it when it
s near my player…
Nothing works. No errors, just nothing happens…
Please help me…
public Rigidbody projectile;
public Transform player;
public float playerDistance;
public float speed = 50;
public float delayTime = 0.5f;
private float counter = 0;
void Start () {
}
void Update () {
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 1400f && counter > delayTime)
{
counter = 0;
Rigidbody instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
}
}
Okay, I see where the problem is now and again, I think you should use Time.time for this functionality.
public float bulletShootInterval = 0.5f;
private float startTime;
void Start()
{
//Get the current time.
startTime = Time.time;
}
void Update()
{
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 1400f && Time.time > startTime)
{
//Perform your stuff here.
Rigidbody instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
//Increment the time variable by the interval.
startTime = Time.time + bulletShootInterval;
}
}
Hope this helps !!
Perhaps this:
public float speed = 50;
public float delayTime = 0.5f;
void Start () {
InvokeRepeating("InstantiateProjectileIfNeeded", 0.0f, delayTime);
}
void InstantiateProjectileIfNeeded()
{
playerDistance = Vector3.Distance (player.position, transform.position);
if (playerDistance < 1400f)
{
counter = 0;
Rigidbody instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
}
Since you want to launch a projectile if a distance is less than 1400 but not too frequently there must be a delay of delayTime
. The following script repeatedly invoke a function after delayTime
and if the distance is less than 1400, your logic should execute and no need of counter
variable i guess.
Hope it helps!
I think you just forget to increment your counter…
void Update () {
playerDistance = Vector3.Distance (player.position, transform.position);
counter += Time.deltaTime;
if (playerDistance < 1400f && counter > delayTime)
{
counter = 0;
Rigidbody instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
}
I hope this help…
NeverHopeless ,
it worked after i added:
void Update(){
InstantiateProjectileIfNeeded ();
}
but the bullet still has no speed. It`s makin instantiate and it works…but I need to make it move. Thank you for your help i really appreciate this .