I’m making a gun turret that shoots towards the player I want the turret and shoot at the player when the players is in range and in line of sight. And my problem is the Raycast isn’t working right, when the turret turns and faces the player the ray faces backwards away from the player, how can I reverse the ray face forward towards the player… I have tried transform.forward * -1 but that didn’t work. I’m out of solutions I need help.
Note: The gun turret object has the AIMove4 script, and it’s parenting several other objects. Could that be the problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIMove4 : MonoBehaviour {
//The turning code
public Transform target;
public float degreePerSecond;
public float ChaseRange = 0;
//The shooting code
public GameObject SpohnPoint; //Bullet Spohn point
public GameObject bulletPrefab01; //Get the bullet prefab
private float CanShoot; //Shooting timer
RaycastHit hit;
// Use this for initialization
void Start () {
CanShoot = 2; //Shoot delay time
}
// Update is called once per frame
void Update ()
{
//Chasing player AI
//Get the distance to the target and check to see if it is close enough to chase
float dist = Vector3.Distance (target.position, transform.position);
//Checks afford close enough to turn and shoot towards the player
if (dist < ChaseRange) {
//Shoots the Raycast beam in the forward direction
if (Physics.Raycast (transform.position, transform.forward, out hit))
{
//If the Raycast hits the object with the player tag do something?
if (hit.collider.gameObject.tag == "Player")
{
Debug.Log ("Raycast");
}
}
Vector3 dirFromMeToTarget = target.position - transform.position;
dirFromMeToTarget.y = 0.0f;
Quaternion LookRotation = Quaternion.LookRotation (dirFromMeToTarget);
transform.rotation = Quaternion.Lerp (transform.rotation, LookRotation, Time.deltaTime * (degreePerSecond / 360.0f));
//The shooting code
CanShoot -= Time.deltaTime;
if (CanShoot <= 0f) {
//Will shoot whichever direction that the blue arrow is facing
GameObject bameObject = Instantiate (bulletPrefab01);
bameObject.transform.position = SpohnPoint.transform.position + SpohnPoint.transform.forward;
bameObject.transform.forward = SpohnPoint.transform.forward;
CanShoot = 2;
}
}
}
}