Ally AI shoot arrow
HI, i'm try to make ally AI that shoot curve or straight arrow to enemy with tag enemy just like archer in Kingdom game My AI code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ally_ThrowPojectile : MonoBehaviour
{
public GameObject projectilePrefab;
public GameObject triggerArea;
public bool inRange = false;
public float launchForce;
float cooldownCounter = 1;
bool coolingdown = false;
void Update()
{
if (!coolingdown && inRange)//shoot when inrange and finish cooldown
{
Shoot();
this.coolingdown = true;
}
else
{
cooldownCounter -= Time.deltaTime;// cooldown
if (cooldownCounter <= 0)
{
cooldownCounter = 1;
coolingdown = false;
}
}
}
void Shoot()
{
float noise = Random.Range(0.1f, 0.9f);
GameObject proj = Instantiate(projectilePrefab, transform.position, Quaternion.identity);
proj.GetComponent<Rigidbody2D>().velocity = transform.right * launchForce;
Destroy(proj, 4.0f);
}
}
My trigger Area code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ally_ThrowP_TriggerAreaCheck : MonoBehaviour
{
private Ally_ThrowPojectile proj;
private void Awake()
{
proj = GetComponentInParent<Ally_ThrowPojectile>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.CompareTag("Enemy"))
{
proj.inRange = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
proj.inRange = false;
}
}
}
My arrow code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Elf_Arrow : MonoBehaviour
{
Rigidbody2D rb;
bool hasHit;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if(hasHit==false)// rotate arrow
{
float angle = Mathf.Atan2(rb.velocity.y, rb.velocity.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
hasHit = true;
rb.velocity = Vector2.zero;
rb.isKinematic = true;
}
}
Comment