0
\$\begingroup\$

Game : bird's eye view (2D)

  1. When I touch the button, my character will teleport a fixed distance in the direction it is facing.

  2. If there is an object at that distance (like a wall) it will not teleport (it can pass through the wall)

For example, the code below teleports the character, but only takes it to the position determined on the stage with the mouse. I also tried the "raycast" system, but the problem is that even if there is an object nearby, the character should be able to teleport from there, it does not provide me with raycast. (because of Raycasthit)

Actually what I think is very simple. Assigning the transform of the point in the direction my character is facing, for example 10 units away, to my character's transform. This way my character will be teleported. However, of course, if there is a collider 10 units away, it cannot teleport, but on the other hand, my character can teleport even if there is a collider object 6 units away. Although it seems simple, I could not do it.

void Update ()
{
   if( Input.GetMouseButtonDown( 0 ) )
   {
    transform.position = Camera.main.ScreenToWorldPoint( new Vector3( Input.mousePosition.x, Input.mousePosition.y, 10 ) );
   }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It looks like you meant to write something like this:

void Update ()
{
   if (Input.GetMouseButtonDown(0))
   {
        var mousePosition = Input.mousePosition;
        mousePosition.z = 10f;

        var facing = Camera.main.ScreenToWorldPoint(mousePosition)- transform.position;
        facing.z = 0f;

        // Get a position a fixed distance in the mouse direction.
        var destination = transform.position + facing.normalized * teleportDistance;

        // Check if there are any obstacles blocking the character from spawning there.
        if (Physics2D.OverlapCircle(destination, characterRadius, obstacleLayers) != null)
        {
            // If not, perform the teleport.
            transform.position = destination;
        }
   }
}
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for your reply. But there is "mouseposition" in the code you suggested. I'm going to assign my function to a button. When I touch the button, the character will teleport to a fixed distance. I think need "mouseposition" information in the code you suggested. \$\endgroup\$
    – gunza
    Aug 30, 2021 at 17:08
  • 1
    \$\begingroup\$ I'm basing it off of the code you showed. If you don't want to use mousePosition, don't show it that way in your question. You can of course replace facing with transform.up or .right etc as you like. \$\endgroup\$
    – DMGregory
    Aug 30, 2021 at 17:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .