Skip to content

Instantly share code, notes, and snippets.

@Drenerdo
Created February 28, 2019 12:24
Show Gist options
  • Save Drenerdo/934cadb4877eba9a9cd16389f69cb8de to your computer and use it in GitHub Desktop.
Save Drenerdo/934cadb4877eba9a9cd16389f69cb8de to your computer and use it in GitHub Desktop.
Enemy AI Shooting
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AI_Shooting_Manager : MonoBehaviour
{
public Transform target;
public Transform bullet_projectile;
public float maxLookDistance = 30;
public float maxAttackDistance = 10;
public float minDistanceFromIsland = 2;
public float rotateDamping = 2;
public float shootInterval = 0.5f;
private float shootTime = 0;
void Update()
{
float distance = Vector3.Distance(target.position, transform.position);
if (distance <= maxLookDistance)
{
LookAtDistance();
}
if (distance <= maxAttackDistance && (Time.time - shootTime) > shootInterval)
{
Shoot();
}
}
void LookAtDistance()
{
var dir = target.position - transform.position;
dir.y = 0;
var rotation = Quaternion.LookRotation(dir);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotateDamping);
}
void Shoot()
{
shootTime = Time.time;
Instantiate(bullet_projectile, transform.position + (target.position - transform.position).normalized, Quaternion.LookRotation(target.position - transform.position));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment