So I’m working on a top-down shooter that only allows for x and z control, but need a way to shoot ground enemies as well.
This code (much of which I “borrowed” from another question here), is designed to find the closest enemy directly in front of the player and adjust the gun’s pitch accordingly. If no enemy is directly ahead, it’s just supposed to fire forward (that part works).
The problems are that it only detects a hit from very close, no matter what I set the ray distance to, and the end points of the rays stay fixed at their initial z position.
Also, any suggestions to clean up my ugly tag check in the linecast would be cool…
I’m sure this is amateur-hour stuff, but any help is appreciated.
#pragma strict
public var maxAngle : float = 180;
public var increments : int = 15;
public var rayDistance : float = 150; //Set to 0 for infinity.
public var sphereCastRadius : float = 2;
public var targetTag01 : String = "Enemy";
public var targetTag02 : String;
public var targetTag03 : String;
function Start ()
{
if (rayDistance == 0)
{
rayDistance = Mathf.Infinity;
}
}
function Update ()
{
}
function LateUpdate ()
{
}
function FixedUpdate()
{
transform.rotation = Quaternion.Euler(0, 0, 0);
RaycastSweep();
}
function RaycastSweep()
{
var startPos : Vector3 = transform.position; // umm, start position !
var targetPos : Vector3 = Vector3.zero; // variable for calculated end position
var startAngle : float = ( -maxAngle * 0.5 ); // half the angle to the Left of the forward
var finishAngle : float = ( maxAngle * 0.5 ); // half the angle to the Right of the forward
// the gap between each ray (increment)
var inc : float = ( maxAngle / increments );
// step through and find each target point
var hit : RaycastHit;
var targetDistance:float = 215;
for ( var i : float = startAngle; i < finishAngle; i += inc ) // Angle from forward
{
targetPos = (Quaternion.Euler( i, 0, 0 ) * transform.forward ).normalized * rayDistance;
// linecast between points
if ( Physics.Linecast(startPos, targetPos, hit) && ((hit.collider.gameObject.tag == targetTag01) || (hit.collider.gameObject.tag == targetTag02) || (hit.collider.gameObject.tag == targetTag03)))
{
var diff = (transform.position - hit.point);
var curDistance = diff.magnitude;
if (curDistance < targetDistance)
{
transform.Rotate(i, 0, 0);
targetDistance = curDistance;
Debug.Log( "Hit " + hit.collider.gameObject.name );
}
// to show ray just for testing
Debug.DrawLine( startPos, targetPos, Color.green );
}
// to show ray just for testing
Debug.DrawLine( startPos, targetPos, Color.red );
}
}