now what i am try to do is to create AI for enemy car in my racing game for that i have to create a path and now i am trying to create sensors in front of my enemy car so that it can dough/avoid collision with those obstacle in front of car and for sensor i am using raycast function in c# but what is happening is my ray is not displaying properly or i can say its start position is ok but end position is not towards on obstacle and its towards terrain’s start position you can also see in pictures
below is my script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CarEngin : MonoBehaviour {
public Transform path;
public Transform[] pathTranform;
private int currentNode = 0;
private List<Transform> nodes;
public float MaxSteerAngle = 45f;
public WheelCollider wheelFL;
public WheelCollider wheelFR;
public WheelCollider wheelBL;
public WheelCollider wheelBR;
public float maxTorque = 50f;
public float distfrompath = 20f;
public int pathTranformLength;
float topSpeed = 150f;
float currentSpeed;
float deaccelrationSpeed = 10;
float frntSensorStartPoint = 5;
float sensorLength = 5;
float frontSensorDist = 5;
// Use this for initialization
void Start () {
Transform[] pathTranform = path.GetComponentsInChildren<Transform>();
nodes = new List<Transform>();
pathTranformLength = pathTranform.Length;
for (int i = 1; i < pathTranform.Length; i++)
{
if (pathTranform *!= path.transform)*
{
nodes.Add(pathTranform*);*
}
print(pathTranform);
}
}
* // Update is called once per frame*
* void FixedUpdate () {*
ApplySteer();
Move();
sensor();
}
void ApplySteer()
{
Vector3 relativeVector = transform.InverseTransformPoint(nodes[currentNode].position.x,transform.position.y, nodes[currentNode].position.z);
//relativeVector = relativeVector / relativeVector.magnitude;
float newSteer = (relativeVector.x / relativeVector.magnitude) * MaxSteerAngle;
wheelFL.steerAngle = newSteer;
wheelFR.steerAngle = newSteer;
if(relativeVector.magnitude <= distfrompath)
{
currentNode++;
if(relativeVector.magnitude >= pathTranformLength)
{
currentNode = 0;
}
}
}
void Move()
{
currentSpeed = 2 * (22 / 7) * wheelBL.radius * wheelBL.rpm * 60 / 1000;
currentSpeed = Mathf.Round(currentSpeed);
if (currentSpeed <= topSpeed)
{
wheelBL.motorTorque = maxTorque;
wheelBR.motorTorque = maxTorque;
wheelBL.brakeTorque = 0;
wheelBR.brakeTorque = 0;
}
else
{
wheelBL.motorTorque = 0;
wheelBR.motorTorque = 0;
wheelBL.brakeTorque = deaccelrationSpeed;
wheelBR.brakeTorque = deaccelrationSpeed;
}
}
void sensor()
{
Vector3 pos;
RaycastHit hit;
pos = transform.position;
pos += transform.forward * frntSensorStartPoint;
if(Physics.Raycast(transform.forward,pos,out hit,sensorLength))
{
Debug.DrawLine(pos,hit.point, Color.red,1000);
}
}
}
alt text