How to cast ray from a object in direction local to that object?

Hi, I m totally new to unity.
I m trying to build AI in car game,
I am firing a ray from enemy car and checking whether there is a object or not.

Ray ray = new Ray(transform.position,transform.forward);
        RaycastHit hit;
        if (Physics.Raycast(ray,out hit,rayDistance)) {
			if(hit.collider.tag == "rail") {
				Debug.Log("AI working");
				transform.Rotate(Vector3.up, 100*speed * Time.deltaTime);

This thing is working. but

Now i am not able to understand how to cast a ray at an angle of 45 degrees to car not world space so that when car take turn the ray still be at 45 degrees to the car.

Check out the Transform docs.

Specifically look at the functions:


Use these functions to convert from Local/World spaces to the other.

Something to consider : If Z is your forward axis, Vector3(1,0,1) would represent a 45 degree angle, forward/right.

Perhaps your could have a child object on the car perform a ray. As the child transform is relative to the parent it will have fixed position to the car.

I don’t want to post a load of code as, from personal experience, it is better to work thee functions out yourself to get to grips with how they work. Have a go, come back if you want further help :slight_smile:

Edit: You can probably use Vector3.Project to achieve your effect.