Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to stop raycast when hitting an object in Unity?

Hi,


in my Unity game (top-down 2D shooter) there are some enemies flying along a path (via DOTween). My player casts a ray into the scene in order to get an enemy-object right in front of the player. So far so good.


Now the problem is that I want only one enemy-object as a result, i.e. the raycast should stop when it hits an enemy-object for the very first time. How do I achieve this?


I need only one enemy-object hit by the raycast because there is a crosshair in my game and when the raycast starts and the enemies fly along the path the crosshair jumps forth and back (and I don't want this - the crosshair should stay at the first enemy hit by the raycast). Any help, please?


Raycast-video


This is my code (attached to the player):


void FixedUpdate() {

//crosshair: Cast a ray straight up.

float _size = 12f;

   Vector2 _direction = this.transform.up;

   RaycastHit2D _hit = Physics2D.Raycast(this.transform.position, _direction, _size);


  if (_hit.collider != null && _hit.collider.tag == "EnemyShipTag") {


   // We touched something!


   Vector2 target = new Vector2(_hit.collider.gameObject.transform.position.x, _hit.collider.gameObject.transform.position.y);


     const float moveTime = 0.1f;

     float step;


   step = Vector2.Distance(crosshairGO.transform.position, target);

     crosshairGO.transform.position = Vector2.MoveTowards(crosshairGO.transform.position, target, step / moveTime * Time.deltaTime);


     Vector2 _pos3 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);

   crosshairGO.transform.position = _pos3;

   crosshairBegin = false;

  } else {

   // Nothing hit


   Vector2 _pos2 = new Vector2(this.transform.position.x, 4.5f);

   if (crosshairBegin) {

   crosshairGO.transform.position = _pos2;

   } else {

   Vector2 _pos4 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);

   crosshairGO.transform.position = _pos4;

   }

  }



}

Sign In or Register to comment.