Managing Raycast Rotations

Hello,

What I’m trying to do is make a sort of Pathing algorithm with using forward/diagonal rays.

Right now my code is : (OLD CODE, working code below)

	void managePathingAndMovement()
	{
		forwardRayCast();
		if (!moveTowardsEnd)
		{
			translate();
		}
	}
	
	private Vector3 moveDirection; //No point in using atm
	void forwardRayCast()
	{
		Ray fowRay = new Ray(_rayCastObject.position, Vector3.forward);
		RaycastHit fowHit;
		if (Physics.Raycast(fowRay, out fowHit, Mathf.Infinity)) 								//Change Mathf.Inf
		{
			transform.eulerAngles = new Vector3(0, transform.eulerAngles.y + 1, 0);  //Sets the y rotation to +1 every frame while stil Raycasting
		}
		else
		{
			moveTowardsEnd = true;
		}
	}
	
	void translate()
	{
		transform.Translate(Vector3.forward * 10 * Time.deltaTime);
	}

I can’t actually rotate the transform itself, and the weird thing is that my Vector3.forward changes as my character rotates, but the Raycast seems to be working independently.

Also, I’ve tried shooting the ray from both the transform itself and the child object. Both times it’s just pointing dead ahead. How would I go about fixing this? – Fixed with multiplication :frowning:

	private Vector3 moveDirection;
	void forwardRayCast()
	{
		moveTowardsEnd = false;
		Vector3 forward = Quaternion.Euler(_rayCastObject.localEulerAngles) * Vector3.forward;    //Rotates toward the localRotation by using eulerAngles
		Ray fowRay = new Ray(_rayCastObject.position,forward );
		RaycastHit fowHit;
		Debug.DrawRay(_rayCastObject.position, forward);
		if (Physics.Raycast(fowRay, out fowHit, Mathf.Infinity)) 								//Change Mathf.Inf
		{
			transform.eulerAngles = new Vector3(0, transform.eulerAngles.y + 1, 0);  //Sets the y rotation to +1 every frame while stil Raycasting
			_rayCastObject.localEulerAngles = transform.localEulerAngles;
		}
		else
		{
			//moveTowardsEnd = true;
		}
	}

In your case, You should use transform.forward, transform.right, and transform.up in oppose to Vector3.up etc.

Vector3.forward is a shorthand of (0, 0, 1). Your Vector3.forward doesn’t change, when you use:

transform.Translate(Vector3.forward * 10 * Time.deltaTime);

what happened is that it will move your transform by Vector3.forward at your transform’s local space. For raycast, you need to work with world space.

If you want to raycast in front of your character/gun/AI, you should use:

Ray fowRay = new Ray(_rayCastObject.position, _rayCastObject.forward);

fowRay will be pointing at the same direction the _rayCastObject’s forward direction is.

If you need to look at other angles other that the 3 axis, you can use:

Vector3 lookAtheGroundInFront = transformObjectThatIsLooking.TranslateDirection( new Vector3( 0, -1, 1 ) );

You can either normalize or not normalize the vector, it is up to you and your calculation.