Raycast only returns null
Hey I am trying to make an ai raycast for to do movement but my raycast is only returning null, i had the code working before and then was working on implementing difficulty to it, for example hard can see further than easy or normal, i then took the raycast and did it on the oposit side also (i was thinking if an ai has been downed but still alive and another ai is near then they can change the target to that ai instead of the player and though if the player was close to their back on the likes of hard it will focus on the player first). After implementing this though now my raycast is always returning empty.
Please help as I have no idea why this is happening, though want to make it custom and not the navmesh as more to talk about in my project basically.
MovementAI Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using System.Reflection;
public class MovementAI : MonoBehaviour {
DifficultyLevel myEnum;
private GameObject target;
public Transform transformDistance;
private AiActionsControl AiActionScript;
private theCloud cloudScript;
// public bool moveObject;
private bool isInPlayersRange, isHitTarget; // if in close enough range will start raycasts on // could do collider on player or get players range may do colider
private bool doOnceBool = true;
public float movementSpeed = 0.25f;
private float targetDirection = -1; // -1 is to the left +1 is to the right
public string targetTagString = "Player";
public float easyLineOfSightDistance = 5, normalLineOfSightDistance = 7.5f, hardLineOfSightDistance = 10;
private float currentLineOfSightDistance = 0;
private float currentLOS2;
public float easyAttackRangeDistance = 3, normalAttackRangeDistance = 2f, hardAttackRangeDistance = 1;
private float currentAttackRangeDistance = 0;
private GroundCollision groundCollisionScript;
private string groundCollisionInstantiateString;
public GameObject goCollis;
// public bool isGrounded;
void Awake()
{
// printError(MethodBase.GetCurrentMethod());
target = GameObject.FindGameObjectWithTag(targetTagString);
if (gameObject.GetComponent<AiActionsControl>() == null)
gameObject.AddComponent<AiActionsControl>();
AiActionScript = GetComponent<AiActionsControl>();
if (gameObject.GetComponentInChildren<GroundCollision>() == null)
Instantiate(goCollis, transform); //(Resources.Load("Assets/GroundCollisionSpriteFeet"));//Prefabs/Managers // gameObject.AddComponent<GroundCollision>();
// Instantiate(goCollis,transform);
groundCollisionScript = GetComponentInChildren<GroundCollision>();
}
void printError(MethodBase functionFrom)
{
string objectName = transform.name.Replace("(Clone)", "");
MonoBehaviour thisScriptName = this.GetComponent<MonoBehaviour>();
Debug.LogWarning("!!! YEAAAA it done goofed, in (" + objectName.ToUpper()
+ ") game object on Script ("
+ this.GetType().ToString().ToUpper()
+ ") In the (" + functionFrom.ToString() + ") function");
}
// Use this for initialization
void Start()
{
cloudScript = FindObjectOfType<theCloud>();
if (cloudScript.GetComponent<theCloud>() == null)
{
// cloudScript.GetComponent<theCloud>();
printError(MethodBase.GetCurrentMethod());
}
}
public float speed;
// Update is called once per frame
void Update()
{
/*
if (Vector3.Distance(transform.position, target.transform.position) < 100)
{
print("player is close");
transform.position = (target.transform.position - transform.position).normalized * speed * Time.deltaTime;
}
else
{
print("not close yet");
print(Vector3.Distance(transform.position, target.transform.position));
}
*/
// if (myEnum != cloudScript.currentDificultyLevelEnum)
// myEnum = cloudScript.currentDificultyLevelEnum;
// if (groundCollisionScript.isGrounded)
{
FindTargetDirection();
searchRaysPatrolStart();
// raycastMethod();
}
}
void FindTargetDirection()
{
if (target.transform.position.x < transform.position.x)
targetDirection = -1; // Target Left
else targetDirection = 1; // Target Right
}
void searchRaysPatrolStart()
{
#region Debug switch difficulty
// this should be searching left and right the range length of sight to see if can see player
// incorperate games difficulty if easy they cant see as far, if hard they can see full screen
if (targetDirection == -1) // left
{
switch (cloudScript.currentDificultyLevelEnum)
{
case DifficultyLevel.Easy:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
currentLineOfSightDistance = easyLineOfSightDistance;
currentAttackRangeDistance = easyAttackRangeDistance;
break;
case DifficultyLevel.Normal:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
currentLineOfSightDistance = normalLineOfSightDistance;
currentAttackRangeDistance = normalAttackRangeDistance;
break;
case DifficultyLevel.Hard:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
currentLineOfSightDistance = hardLineOfSightDistance;
currentAttackRangeDistance = hardAttackRangeDistance;
break;
default:
printError(MethodBase.GetCurrentMethod());
break;
}
}
else
{// 1 equals to the right
switch (cloudScript.currentDificultyLevelEnum)
{
case DifficultyLevel.Easy:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
break;
case DifficultyLevel.Normal:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
break;
case DifficultyLevel.Hard:
Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
break;
default:
printError(MethodBase.GetCurrentMethod());
break;
}
}
#endregion
#region past workings
/*
switch(cloudScript.DifficultyLevel) { case theCloud.DifficultyLevel.Easy: break;
} */
/*
switch (cloudScript.currentDifLevelInt)
{
case 1:
currentLineOfSightDistance = -easyLineOfSightDistance;
break;
case 2:
currentLineOfSightDistance = -normalLineOfSightDistance;
break;
case 3:
currentLineOfSightDistance = -hardLineOfSightDistance;
break;
default:
printError(MethodBase.GetCurrentMethod());
break;
}
switch (cloudScript.currentDifLevelInt)
{
case 1:
currentLineOfSightDistance = easyLineOfSightDistance;
break;
case 2:
currentLineOfSightDistance = normalLineOfSightDistance;
break;
case 3:
currentLineOfSightDistance = hardLineOfSightDistance;
break;
default:
printError(MethodBase.GetCurrentMethod());
break;
}
*/
// switch(cloudScript.currentDificultyLevelEnum)
// {
// case cloudScript.currentDificultyLevelEnum.ToString().Equals("Easy"):
// Debug.LogWarning(" MOVE AI IS SET TO EASY");
// break;
// default:
// Debug.LogWarning(" MOVE AI IS not SET TO EASY");
// break;
// }
//sight 10 hard
// if (myEnum == DifficultyLevel.Easy)
// {
// Debug.Log("!!!!!!!!!!!" + myEnum);
// }
// if (myEnum == DifficultyLevel.Easy)
// {
// Debug.Log("!!!!!!!!!!!" + myEnum);
// }
#endregion
// float currentLoSDistance2;
#region Actual Workings
if (targetDirection < 0)
{
// targetDirection = -1 minus 1 is left
// currentAttackRangeDistance = easyAttackRangeDistance normalAttackRangeDistance hardAttackRangeDistance
/*
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Easy)
{
currentLineOfSightDistance = transform.position.x - easyLineOfSightDistance;
// currentLineOfSightDistance = easyLineOfSightDistance;
currentAttackRangeDistance = easyAttackRangeDistance;
}
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Normal)
{
currentLineOfSightDistance = normalLineOfSightDistance;
currentLineOfSightDistance = transform.position.x - normalLineOfSightDistance;
currentAttackRangeDistance = normalAttackRangeDistance;
}
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Hard)
{
currentLineOfSightDistance = hardLineOfSightDistance;
currentLineOfSightDistance = transform.position.x - hardLineOfSightDistance;
currentAttackRangeDistance = hardAttackRangeDistance;
}
}
else
{
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Easy)
{
currentLineOfSightDistance = transform.position.x + easyLineOfSightDistance;
// currentLineOfSightDistance = easyLineOfSightDistance;
currentAttackRangeDistance = easyAttackRangeDistance;
}
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Normal)
{
// currentLineOfSightDistance = normalLineOfSightDistance;
currentLineOfSightDistance = transform.position.x + normalLineOfSightDistance;
currentAttackRangeDistance = normalAttackRangeDistance;
}
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Hard)
{
// currentLineOfSightDistance = hardLineOfSightDistance;
currentLineOfSightDistance = transform.position.x + hardLineOfSightDistance;
currentAttackRangeDistance = hardAttackRangeDistance;
}
//currentLineOfSightDistance = -currentLineOfSightDistance;
*/
}
currentLOS2 = currentLineOfSightDistance * -1;
#endregion
#region Past Workings 2
// RaycastHit2D oposTestRayHit2D = Physics2D.Linecast(transform.position, new Vector3(transform.position.x + currentLOS2, transform.position.y, 0), gameObject.layer - 3); // transformDistance.position)
// Debug.DrawLine(transform.position, new Vector3(transform.position.x + currentLOS2, transform.position.y, 0), Color.blue); //new Vector3( transform.position.x-5, transform.position.y,0), Color.yellow);
// Raycast2D rayName =(new Vector3(gameObject.transform.x, gameObject.transform.y, 0), new Vector3(currentLineOfSightDistance, gameObject.transform.y, 0) end, GameObject.layer)
// Debug.DrawLine(gameObject.transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), Color.green);
// Debug.Log("!!!!!!!!!!!!" + cloudScript.currentDificultyLevelEnum);
// this part ends after they see the player (a collision, left or right, hits the player then turns off other side,
// if hit left turns off right save resources, and starts moving towards if still hitting)
// will also start a in range check of another raycast (or get distance whatever is least demand though raycast
// could do ai help each other or ai companion of player)
// this will be one unit above (or however is is enough to not collide with the )
#endregion
// raycastMethod();
customRaycastStuff();
}
public string stringOfLayerNameToIgnore = "GroundTop"; // this can be changed
public RaycastHit2D testRayHit2D;
private LayerMask thisLayerMask;
void customRaycastStuff()
{
thisLayerMask = 1 << gameObject.layer; //LayerMask.NameToLayer(stringOfLayerNameToIgnore);
Debug.DrawRay(transform.position, new Vector3(targetDirection, 0, 0) * currentLineOfSightDistance, Color.yellow); // Yellow is Sight
// RaycastHit2D testRayHit2D = Physics2D.Linecast(transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), gameObject.layer - 3); // transformDistance.position)
testRayHit2D = Physics2D.Linecast(transform.position, new Vector3(targetDirection, 0, 0) * currentLineOfSightDistance, 1 << LayerMask.NameToLayer("GroundTop") | 1<< LayerMask.NameToLayer("GroundMid") | 1 << LayerMask.NameToLayer("GroundBottom") | 1 << LayerMask.NameToLayer(stringOfLayerNameToIgnore));
if (testRayHit2D.collider == null)
Debug.LogWarning("IT HIT nothing LEFT : " + testRayHit2D);
if (testRayHit2D.collider != null)
{
if (testRayHit2D.collider.tag == "Player") ;
Debug.Log("IT HIT THE PLAYER ON LEFT : "+testRayHit2D);
}
}
void raycastMethod()
{
// Within this I will use the values to flip to make sure that it is both a) easier to read and understand for when i enevatably have to backtrack and b) easier on resources
// My default thinking though is that the enemy is on the right looking to the target on its left
Vector3 raySpawnPointLeft = new Vector3(0, 0, 0); // This is the point that the ray will start at, gun nosel
raySpawnPointLeft = transform.position;
Vector3 rayShootDirectionLeft = new Vector3(targetDirection, 0, 0); // This is the direction the ray will go out to, bullet trail
Vector3 rayShootDirectionRight = new Vector3(-targetDirection, 0, 0); // This is the direction the ray will go out to, bullet trail
RaycastHit leftRayHitInfo, rightRayHitInfo;
float distanceToShootTheRay;
distanceToShootTheRay = currentLineOfSightDistance;
// currentLineOfSightDistance
if (targetDirection < 0)
{
// targetDirection = -1 minus 1 is left
// currentAttackRangeDistance = easyAttackRangeDistance normalAttackRangeDistance hardAttackRangeDistance
if (cloudScript.currentDificultyLevelEnum == DifficultyLevel.Easy)
{
}
}
int currentLayerToIgnoreSelf = gameObject.layer - 3; // this worked with linecasts dont know about raycasts
/*
if(targetDirection<0)//left
{
rayShootDirectionLeft = new Vector3(-1, 0, 0);
}
else
{
rayShootDirectionLeft = new Vector3(1, 0, 0);
}
*/
/*
Debug.DrawRay(raySpawnPointLeft, rayShootDirectionLeft * distanceToShootTheRay, Color.blue);
// THIS DIDNT WORK BUT SECOND DID
Ray leftRayCastLineOfSight = new Ray(raySpawnPointLeft, rayShootDirectionLeft); // This is to be used in the raycast to make it look cleaner
// Physics.Raycast(leftRayCastLineOfSight, RaycastHit leftRayHitInfo, float distance, int LayerMask);
Physics.Raycast(leftRayCastLineOfSight, out leftRayHitInfo, distanceToShootTheRay, currentLayerToIgnoreSelf);
// if (leftRayHitInfo.collider.tag != null)
// if (leftRayHitInfo != null && leftRayHitInfo.collider != null)
*/
Debug.DrawRay(transform.position, new Vector3(targetDirection, 0, 0) * currentLineOfSightDistance, Color.yellow); // Yellow is Sight
Ray leftRayCastLineOfSight = new Ray(raySpawnPointLeft, rayShootDirectionLeft); // This is to be used in the raycast to make it look cleaner
// Physics.Raycast(leftRayCastLineOfSight, RaycastHit leftRayHitInfo, float distance, int LayerMask);
Physics.Raycast(transform.position, new Vector3(targetDirection, 0, 0), out leftRayHitInfo, currentLineOfSightDistance);
Debug.DrawRay(transform.position, new Vector3(targetDirection * -1, 0, 0) * currentLineOfSightDistance, Color.blue); // Yellow is Sight
Ray rightRayCastLineOfSight = new Ray(raySpawnPointLeft, rayShootDirectionRight); // This is to be used in the raycast to make it look cleaner
Physics.Raycast(transform.position, new Vector3(targetDirection, 0, 0), out rightRayHitInfo, currentLineOfSightDistance);
if (transform == null)
{
Debug.Log("transform is null");
}
if (leftRayHitInfo.collider == null)
{
Debug.LogError("leftRayHitInfo.collider is null " + leftRayHitInfo.collider);
}
if (leftRayHitInfo.collider != null)
{
Debug.LogError(leftRayHitInfo);
if (leftRayHitInfo.collider.tag == target.tag) //"Player")
{
isHitTarget = true;
if (AiActionScript.canMoveObject)
{
// transform.position = new Vector3(transform.position.x * -movementSpeed, transform.position.y, 0);
transform.Translate(Vector3.right * targetDirection * movementSpeed);
}
else
{
isHitTarget = false;
}
}
}
// else printError(MethodBase.GetCurrentMethod());
// if (rightRayHitInfo.collider != null)
// {
/*
if (leftRayHitInfo.collider == null)
{
Debug.LogError("transform is null");
}
if (leftRayHitInfo.collider.tag != null)
{
// if (rightRayHitInfo.collider.tag == target.tag)//"Player")
{
}
}
else printError(MethodBase.GetCurrentMethod());
// RaycastHit2D testRayHit2D = Physics2D.Linecast(transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), gameObject.layer - 3); // transformDistance.position)
// Debug.DrawLine(transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), Color.yellow); //new Vector3( transform.position.x-5, transform.position.y,0), Color.yellow);
// I understand it would be better doing 1 single raycast from left point to right point instead of transform to left and transform to right but this is easier to think through for myself
// (more demanding and easily fixed) but if i can get this to work and have time i will go back and optamize this
#region Past Workings
// RaycastHit2D testRayHit2D = Physics2D.Linecast(transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), gameObject.layer - 3); // transformDistance.position)
// Debug.DrawLine(transform.position, new Vector3(currentLineOfSightDistance, transform.position.y, 0), Color.yellow); //new Vector3( transform.position.x-5, transform.position.y,0), Color.yellow);
// Debug.Log("!!!!DFFFFFFFFFD!!!!! " + testRayHit2D.distance);
/*
if (testRayHit2D.collider != null)
{
// if (testRayHit2D.collider.name != "PlayerRangeRays")
if (testRayHit2D.collider.tag == target.tag) // == target.
{
isHitTarget = true;
if (AiActionScript.canMoveObject)
{
// transform.position = new Vector3(transform.position.x * -movementSpeed, transform.position.y, 0);
transform.Translate(Vector3.right * targetDirection * movementSpeed);
}
}
else
{
isHitTarget = false;
}
}
Debug.Log(testRayHit2D.collider);
if (!isHitTarget)
if (testRayHit2D.distance >= 2.25)
{
if (!doOnceBool)
doOnceBool = true;
}
if (isHitTarget)
{
if (testRayHit2D.distance <= 2.25)
{
if (doOnceBool)
{
doOnceBool = false;
movementSpeed = movementSpeed / 3;
// AiActionScript.PickAction();
}
}
// rb.velocity = new Vector3(-movementSpeed, 0, 0);
}
*/
// #endregion
}
}
Your answer
Follow this Question
Related Questions
Trouble making jumping spider enemies 0 Answers
AI disappears when moving. 1 Answer
Occasional NavMeshAgent gets stuck and goes the wrong direction 1 Answer
How change the destination point if it is inside an obstacle? 0 Answers
Problem making object keep on RaycastHit point relative to another object 0 Answers