# Unity 2D Teleport!

Good day ! I’m working on a 2D platformer game and I want to teleport my character using a specific key(for exemple ‘X’).When I press X the main character will be teleported left or right(in Update function I have a variable who tells me the right way).So I used DrawCast(because I couldn’t fiind a working Raycast algorithm working on 2D),and the character teleports using transform.translate.Everything is working properly,but I have some particular cases.For exemple if there is a collider in front of the character,I want to calculate how far can I teleport my player.But I can’t do it.I tried to reduce the ‘draw line’,using alternative variables,but it is not working properly.Please tell me what should I to be able to calculate the properly distance to teleport my player near the collider,so as they don’t overlap. Please tell me what should I do!

Here is the code:

void Raycasting()
{
Debug.DrawLine (lineStart.position, lineEnd.position, Color.green);
if (Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer (“Colliders”)))
{
whatIHit = Physics2D.Linecast (lineStart.position, lineEnd.position, 1 << LayerMask.NameToLayer (“Colliders”));
interact = true;

} else
{
interact = false;
}
if (Input.GetKeyDown (KeyCode.X) && interact == false) {
if (lastKey == KeyCode.RightArrow) {
transform.Translate (distance, 0, 0);
} else {
if (lastKey == KeyCode.LeftArrow) {
transform.Translate (-distance, 0, 0);
}
}
}
else
{
if(Input.GetKeyDown(KeyCode.X) && interact == true)
{
if(lastKey == KeyCode.RightArrow)
{
lineEndCopy = lineEnd;
distanceCopy = distance;
contor = 0;
{
Vector3 temp = new Vector3(0.3f,0,0);
contor++;
lineEndCopy.transform.position -= temp;
distanceCopy -= 1;

}
transform.Translate (distanceCopy, 0, 0);

Vector3 temp1 = new Vector3(0.3f * contor,0,0);
lineEnd.transform.position += temp1;
}
}

}
}
}

There is 2D raycasting. You could do something like this to check for potential collisions in the players path while teleporting :

``````    public LayerMask TerrainMask;
public int FacingDirection; //-1 = left, 1 = right
public float MaxTeleportDistance; //max distance the player can teleport

void Teleport()
{
RaycastHit2D rayHit = Physics2D.Raycast(transform.position,
if (rayHit)
{
// RayCastHit2D.fraction will give you the length of the ray minus any collision depth
transform.Translate(new Vector3(FacingDirection * rayHit.fraction, 0, 0));
}
else
{
transform.Translate(
new Vector3(FacingDirection * MaxTeleportDistance, 0, 0));
}
}
``````

Note, this is pseudo-code and I have not tested it!

1 Like

Thank you very much sir!