I have been on this problem for over a day now and exhausted every variation of RaycastHit2D. I will try to explainIn my situation to2D game, the best to my ability. The player is able to teleport to any place on the screen with the click of the mouse button. What I am trying to preventprevent is the ability to teleport across solid objects. If the point from the player and the mouse click position is across an object then I want the player to teleport nextnext to that object instead of across it.
I am currently trying to achieve this with Raycasting, since from what I understand is that it draws an imaginary line from the origin and a given direction from that pointraycasting. The code I wrote somewhat works but only if the mouseclickmouse click is on an object, if the mouseclickmouse click is across another object, it still teleports me accross the object without it registering that there is an object between the player and the mouse position. The object is on layer 0.
My code:
Vector3 player_position = Camera.main.WorldToScreenPoint(transform.position);
Vector3 to_object_vector = transform.position - Camera.main.transform.position;
Vector3 linear_distance_vector = Vector3.Project(to_object_vector, Camera.main.transform.forward);
float distance_to_camera = linear_distance_vector.magnitude;
Vector3 mouse_position = Input.mousePosition;
float dist = Vector2.Distance(player_position, mouse_position);
Vector3 dir = (mouse_position - player_position).normalized;
mouse_position.z = distance_to_camera;
RaycastHit2D hit = Physics2D.Raycast(new Vector2(player_position.x, player_position.y), new Vector2(dir.x, dir.y), dist, 0);
if (hit.collider != null) {
Debug.Log(hit.point);
mouse_position = new Vector3(hit.point.x, hit.point.y, mouse_position.z);
}
Again it works only if the mouse position is on another object and teleports me next to the object instead of inside the collider, but if I click across the object I teleport across it. Is my idea of raycasting wrong because I thought it gives you the position point if there is an object in the way of the origin and direction? Because I don't see why else it would not work unless my if statement is not checking for thata better approach to this problem?! Thank you in advance for any replies!