- Home /
Question by
ABOSamantha · Feb 22, 2021 at 08:02 PM ·
c#script.
How to make a Turret shoot the x-axis
public float Range;
public Transform Target;
bool Detected = false;
public GameObject Gun;
public GameObject Bullet;
public float fireRate;
public float Force;
float nexTimeToFire = 0;
public Transform ShootPoint;
Vector2 Direction;
public GameObject alaramlight;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 targetPos = Target.position;
Direction = targetPos - (Vector2)transform.position;
RaycastHit2D rayinfo = Physics2D.Raycast(transform.position, Direction, Range);
if (rayinfo)
{
if (rayinfo.collider.gameObject.tag == "Player")
{
if(Detected == false)
{
Detected = true;
alaramlight.GetComponent<SpriteRenderer>().color = Color.red;
}
}
else
{
if (Detected == true)
{
Detected = false;
alaramlight.GetComponent<SpriteRenderer>().color = Color.black;
}
}
}
if (Detected)
{
Gun.transform.position= Direction;
if (Time.time > nexTimeToFire)
{
nexTimeToFire = Time.time +0.1f/ fireRate;
shoot();
}
}
}
void shoot()
{
GameObject Bulletins = Instantiate(Bullet, ShootPoint.position, Quaternion.identity);
Bulletins.GetComponent<Rigidbody2D>().AddForce(Direction * Force);
}
void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position,Range);
}
Comment