How to make a smooth crosshair-animation in Unity3D?

Hi,

in Unity 3D I’d like to create a crosshair for my top-down 2D-shooter that gradually moves to its target whenever the player has the same x-position as the target.

The problem is that I want a smooth animation when the crosshair moves to the target. I have included a small gif from another game that shows a crosshair I’d like to achieve. Have a look at it: crosshair-video

I tried to do that with the following script but failed - the crosshair jumps forth and back when the enemies appear. It doesn’t look so smooth like in the video I mentioned above. Any help, please?

The following script is attached to the player:

 [SerializeField]
 private GameObject crosshairGO;
 [SerializeField]
 private float speedCrosshair = 100.0f;

 private Rigidbody2D crosshairRB;
 private bool crosshairBegin = true;

 void Start () {

crosshairRB = crosshairGO.GetComponent<Rigidbody2D>();
crosshairBegin = true;
 }

 void FixedUpdate() {
//Cast a ray straight up from the player
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!
    	Debug.Log("we touched the enemy");
	
		Vector2 _direction2 = (_hit.collider.gameObject.transform.position - crosshairGO.transform.position).normalized;
		crosshairRB.velocity = new Vector2(this.transform.position.x, _direction2.y * speedCrosshair);
		crosshairBegin = false;
    } else {
    	// Nothing hit
    	Debug.Log("nothing hit");
    	crosshairRB.velocity = Vector2.zero;
    	Vector2 _pos2 = new Vector2(this.transform.position.x, 4.5f);
		if (crosshairBegin) crosshairGO.transform.position = _pos2;
    }
}

You should be able to just interpolate the Y coordinate to the target’s position. You can use crosshair.transform.position = new Vector2(crosshair.transform.position.x, Mathf.Lerp(crosshair.transform.position.y, targetY, Time.deltaTime)); to achieve this.
If the rigidbody is strictly required for other functionality, I’m not sure if my answer will work without side effects but its certainly still worth a try.