Shoot towards target
I have a script on my a cube I'm using as a projectile spawner (child object of my enemy). The object of the script is to shoot towards the player if the player is within range. The code works, but I'm having an issue where the cube rotates weird and sometimes shoots off into different directions. I want it to only have the ability to angle up/down to shoot towards the players current position and I'm at a loss. I've tried a few different things with varied wrong results. Any input would be great!
This is a 2.5D game, so the player/enemies move along the X axis. The problem I keep getting is that I want the enemies being able to adjust up/down, but not into the Z and shoot the projectiles off of the course area.
#region Variables
public Transform target;
public float fireSpeed;
public float fireRate;
public Rigidbody fireProjectile;
public float range;
public float distance;
private float lastShotTime = float.MinValue;
private int bulletSpeed = 100;
#endregion
#region Start
void Start()
{
}
#endregion
#region Update
void Update()
{
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
//rotation.y = transform.rotation.y;
//rotation.x = 0;
rotation.z = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * fireSpeed);
distance = Vector3.Distance(transform.position, target.position);
if (distance < range && Time.time > lastShotTime + (3.0f / fireRate) && playerSeen)
{
lastShotTime = Time.time;
LaunchProjectile();
}
}
#endregion
#region LaunchProjectile
void LaunchProjectile()
{
Rigidbody shot = Instantiate(fireProjectile, transform.position + (transform.forward * 0.5f), transform.rotation) as Rigidbody;
shot.velocity = transform.forward * bulletSpeed * Time.deltaTime;
}
#endregion
Your answer
Follow this Question
Related Questions
Can't make my AI shoot projectiles with raycast 0 Answers
making a boomerang effect in a 2D enviorment 1 Answer
Projectile trajectory based on angle 0 Answers
Per Frame BoxColliders? 0 Answers