Created
February 28, 2019 12:24
-
-
Save Drenerdo/934cadb4877eba9a9cd16389f69cb8de to your computer and use it in GitHub Desktop.
Enemy AI Shooting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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