- Home /
Enemy Shooting Through Raycasts
I am trying to learn C#, and am very much a beginner. I am trying to make a stealth-like game, and am trying to make the enemies shoot at the player. If the player is in the enemy "sight", the enemies should face toward the player and shoot him/her. This is the first time I have used raycasting, so the error may be obvious. Here is my enemy sight script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Sight : MonoBehaviour {
public GameObject Player;
public FollowPath FllwPth;
public GameObject SightOwner;
Vector3 PPosition;
public float Damage = 10f;
public float ImpactForce = 250;
public ParticleSystem MuzzleFlash;
public GameObject Impact;
public FPControl PlayerScript;
public GameObject Emitter;
// Use this for initialization
void Start ()
{
Player = GameObject.FindGameObjectWithTag ("Player");
FllwPth = SightOwner.GetComponent<FollowPath> ();
PlayerScript = Player.GetComponent<FPControl> ();
}
// Update is called once per frame
void OnTriggerEnter (Collider other)
{
if (other.tag == "Player")
{
FllwPth.enabled = false;
SightOwner.transform.LookAt (Player.transform.position);
}
}
void OnTriggerStay ()
{
PPosition = Player.transform.position;
ShootAtPlayer ();
}
void OnTriggerExit ()
{
SightOwner.transform.LookAt (PPosition);
}
void ShootAtPlayer()
{
MuzzleFlash.Play ();
RaycastHit PlayerHit;
if (Physics.Raycast (Emitter.transform.position, Emitter.transform.forward, out PlayerHit))
{
Debug.Log (PlayerHit.transform.name);
Target target = PlayerHit.transform.GetComponent<Target> ();
if (target != null)
{
target.TakeDamage (Damage);
}
GameObject TempImpact = Instantiate (Impact, PlayerHit.point, Quaternion.LookRotation (PlayerHit.normal));
Destroy (TempImpact, 2f);
}
}
}
I will accept any advice you can give, thank you :)
Comment
Your answer
Follow this Question
Related Questions
My Projectile System has Another Bug 1 Answer
Limited ammo from Raycast? 1 Answer
Raycast from an objects co-ordinates 1 Answer
Why does the wrong enemy die with this raycast? C# 2 Answers
Multiple Cars not working 1 Answer