- Home /
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: https://imgur.com/a/KBngql8
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;
}
}
}
Your chain of enemies has some gaps in it, and the raycast is going through the gaps in the colliders. To stop the jumping, try making the colliders larger or the enemies closer together.
If you want the raycast to stay at the first enemy, then you have to store the transform of the first enemy you hit. Then check if the enemy still exists and move the crosshair to the position of the stored transform. If the enemy doesn't exist anymore, then use raycast to find more enemies.
Wow! Very interesting because I didn't realize that the gaps could be the problem. So I think I have to make them bigger - if I place the enemies closer together it might look silly. I will check this out ASAP! Thanks for this great hint, man!:)