How can I offset a raycast along the transform's local x/z axis?

What I am trying to achieve:

alt text

If I need to shoot say 3 raycasts (C#): 1 from transform.position (blue line), 1 to the left of this by an offset of lets say 2 units (left yellow line), and 1 to the right by the same offset (right yellow line), how can I do this? I imagine it could be something like:

transform.position + publicVariable (and)

transform.position - publicVariable

Here is my script:

using UnityEngine;
using System.Collections;

public class EnemyAI3 : MonoBehaviour {
	public Transform target;
	public int raycastLength = 1;
	public float leftRaycast = 2f;
public float rightRaycast = -2f;
	
	public bool raycastHitting = false;
    public bool raycastHittingL = false;
	public float turnSpeed = 5;
	   	
	private Transform myTransform;
	
	void Awake() {
		myTransform = transform;
	}

	// Use this for initialization
	void Start () {
		GameObject go = GameObject.FindGameObjectWithTag("Player");
		target = go.transform;
		leftRaycast.x -= 2;
		rightRaycast.x += 2;
	}
	
	// Update is called once per frame
	void FixedUpdate () {

		//Start Raycast forward
		if(Physics.Raycast(myTransform.position, myTransform.forward, raycastLength)){
			Debug.DrawLine(myTransform.position, myTransform.forward, Color.blue);
			myTransform.Rotate(Vector3.up, -90 * turnSpeed * Time.smoothDeltaTime);
			raycastHitting = true;
			
		}
		if(!Physics.Raycast(myTransform.position, myTransform.forward, raycastLength)){
			raycastHitting = false;	
		}
		//End Raycast
		
		

        //Start Raycast Left
		if(Physics.Raycast(myTransform.position, myTransform.right * leftRaycast, raycastLength)){
			Debug.DrawLine(myTransform.position, myTransform.right * leftRaycast, Color.yellow);
			myTransform.Rotate(Vector3.up, 90 * turnSpeed * Time.smoothDeltaTime);
			raycastHittingL = true;
			
		}
		if(!Physics.Raycast(myTransform.position, myTransform.right * leftRaycast, raycastLength)){
			raycastHittingL = false;	
		}
		//End Raycast
	}
}

What is the best way to do this?

  • The class Transform don't have an x property, but a position, which is a Vector3 and have an x property.
  • You them any. If I understand correctly, you want to cast three parallele rays from position with an offset on x. In that case, declare two public float offset1, offset2, then your three rays' origines will be

` transform.position + transform.right * offset1; // for instance, offset1 = -2

transform.position + transform.right;    

transform.position + transform.right * offset2; // for instance, offset2 = 2

`

  • If you need the case where the ray don't hit anything, do not cast it again with !, use else instead.
  • By using the same bool for all the rays (raycastHitting), it's will always take the last value, hiding the other. Just in case you need that bool, which you don't in the ewample above.