Check if the raycast hit something on the way

Hey,

So for school I have to make a 2D platformer and I thought of this game where you teleporting is key, but I want to prevent teleporting through walls.

Vector3 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Debug.DrawLine(player.position, new Vector3(mousePos.x, mousePos.y, player.position.z));
if (Input.GetMouseButtonDown (0)) {
	RaycastHit2D rayCast = Physics2D.Raycast(mousePos, Vector2.zero);
		if(rayCast.collider == null) {
			player.position = new Vector3(mousePos.x,mousePos.y,player.position.z);
		} else {
			Debug.Log ("Struck something at: " + rayCast.collider.gameObject.transform.position);
		}
		//Debug.Log("Position " + mousePos);
}

This detects if I click on something. However I also want it to detect anything in between my player and the position of the mouse.

Greetings, Ferdi

Gotta pay more attention to method’s description. In the Raycast method the first argument is origin of the ray, which is the position of the player, not the position of the mouse. And the direction is not Vector2.zero, but click position - player position. Also you have to set the distance argument otherwise it’ll default to Infinity, so it’ll probably hit something in the game world.

RaycastHit2D hit = Physics2D.Raycast(player.position, mousePos - player.position, (mousePos - player.position).magnitude);

if (hit.collider != null){
    print("Hit: " + hit.collider.gameObject.name);
}else{
    player.position = mousePos;
}