Raycast to follow an object on one axis, and another on a different axis

Hi there.

Right now I’m trying to get a raycast to always aim straight ahead of it’s origin point, but be able to angle up and down on a single axis depending on where a separate object is located.

I’ve thought I had it numerous times, but I seem to be pulling up just short of a solution. I’m using DrawLine to see what I’m doing for the moment. Here’s my current attempt, with all the irrelevant stuff cut out:

var weaponFocus =         bulletTarget.transform.position; //This is the object the ray should be following.
var rayCastPos =          weaponRifle.transform.position;
var weaponDirection =     weaponRifle.TransformDirection(Vector3.up); //The model I'm using has it's up position at the end of the barrel, so Vector3.up is actually forward. Woops.
var weaponFocusLimitedX = weaponDirection.x;
var weaponFocusLimitedY = weaponDirection.y;
var weaponFocusLimitedZ = weaponDirection.z;

Debug.DrawLine(rayCastPos,Vector3(weaponFocusLimitedX,weaponFocusLimitedY,weaponFocus.z).normalized * 100, Color.red,0.0,true);

The basics of what I’m trying to accomplish here is to have the ray head straight forward from the weapon, but be able to move up and down to follow a target. I don’t want it following the target left or right, however.

Any help with this is greatly appreciated.

Okay. Given your description, I’m assuming you are projecting a targeting point into 3D space from the mouse. I’m also going to assume you’ve fixed your rotation, since dealing with a non-standard rotation is difficult for me to think through.

  • hitPoint - the point projected into 3D space by the mouse position
  • adjustedPoint - a point in front of the gun to use for your targeting
  • adjustedDir - the direction from the gun to the point (may not need)

var pt : Vector3 = ProjectPointOnPlane(gun.up, gun.position, hitPoint);
var fwdDist : float = (pt - gun.position).magnitude;
var up : Vector3 = (hitPoint - pt);
var adjustedPt : Vector3 = gun.forward * fwdDist + up;
var adjustedDir : Vector3 = adjustedPt - gun.position;

function ProjectPointOnPlane(planeNormal : Vector3 , planePoint : Vector3 , point : Vector3 ) : Vector3 {
	planeNormal.Normalize();
	var distance = -Vector3.Dot(planeNormal.normalized, (point - planePoint));
	return point + planeNormal * distance;
}

This (untested) code works by swinging the targeting point you get from your mouse around so that it is in front of the camera. It gives you a point to aim at or to use in a Linecast() or as a step in creating a direction.