In my 2D game, the player is able to teleport to any place on the screen with the click of the mouse button. What I am trying to prevent 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 next to that object instead of across it.
I am currently trying to achieve this with raycasting. The code I wrote somewhat works but only if the mouse click is on an object, if the mouse 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.
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);
}
Is there a better approach to this problem?
SpriteRenderer
then assignvelocity
to that direction and then check for the collision \$\endgroup\$