I’m making a game where the player is driving a car with a mounted gun and is being chased by other cars with guns. (Sounds dumb i know) Anyway, you won’t be able to aim the gun very well so I want it to work in a way that allows you to shoot the nearest enemy by pressing the shoot button and for you to never miss. So essentially homing bullets. This will be the only way to make the game playable. This script is what I have so far but I’m really new to coding and I’ve gotten stuck. Thanks.
public class Gun1 : MonoBehaviour
{
public float lookRadius = 10.0f;
public Transform target;
public GameObject gun;
public ParticleSystem muzzleFlash;
public GameObject projectile;
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (Input.GetButtonDown("Jump"))
{
Shoot();
}
if (Input.GetButtonDown("Jump"))
{
Instantiate(projectile, gun.transform.position, Quaternion.identity);
}
if (distance <= lookRadius)
{
Vector3 direction = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
}
}
void Shoot()
{
Instantiate(muzzleFlash, gun.transform.position, gun.transform.rotation);
Destroy(this.muzzleFlash, 0);
RaycastHit hit;
if (Physics.Raycast(gun.transform.position, gun.transform.forward, out hit))
{
Debug.Log(hit.transform.name);
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, lookRadius);
}
}