Hi l am looking for a way to make enemy only only target and shoot player when player has entered trigger.Here is my script.
public Rigidbody bulletPrefab;
public float shootSpeed = 300;
void OnTriggerEnter(Collider other)
{
if(other.tag == "player")
{
shootBullet();
}
}
void shootBullet()
{
var projectile = Instantiate(bulletPrefab, transform.position, transform.rotation);
//Shoot the Bullet in the forward direction of the player
projectile.velocity = transform.forward * shootSpeed;
},Hi l am looking for a way to make my enemy shoot only player when player has entered trigger. Here is my script.
Enemy Script.
public Rigidbody bulletPrefab;
public float shootSpeed = 300;
void OnTriggerEnter(Collider other)
{
if(other.tag == "player")
{
shootBullet();
}
}
void shootBullet()
{
var projectile = Instantiate(bulletPrefab, transform.position, transform.rotation);
//Shoot the Bullet in the forward direction of the player
projectile.velocity = transform.forward * shootSpeed;
}
Need add collision for trigger enemy shoot, idk you already put or not, just make sure you need 2 collisons in enemy, for enamy can shoot and when enemy get shoot/attacked. the easy one is put in GameObject into child, and give it collsion, and the parent get reference from it.
Need more adjust direction for object like Player / enemy / projectile, if you already adjustment for player and enemy, you can get it direction from it, cause you did not show up the code for it, i just can say that.
There are a couple of things that you are missing. First, with the current code the enemy will shoot the player only once/trigger enter which might not be the desired behaviour and second, the bullet is fired using the enemy forward direction but the enemy is not rotated towards the player. Try the following code:
public Rigidbody bulletPrefab;
public float shootSpeed = 300;
private bool playerInRange = false;
private float lastAttackTime = 0f;
private float fireRate = 0.5f; //how many bullets are fired/second
private Transform player = null;
void OnTriggerEnter(Collider other)
{
if(other.tag == "player")
{
playerInRange = true;
player = other.transform;
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "player")
{
playerInRange = false;
player = null;
}
}
void Update()
{
if (playerInRange)
{
//Rotate the enemy towards the player
transform.rotation = Quaternion.LookRotation(player.position - transform.position, transform.up);
if (Time.time - lastAttackTime >= 1f/fireRate)
{
shootBullet();
lastAttackTime = Time.time;
}
}
}
void shootBullet()
{
var projectile = Instantiate(bulletPrefab, transform.position, transform.rotation);
//Shoot the Bullet in the forward direction of the player
projectile.velocity = transform.forward * shootSpeed;
}