- Home /
Getting stuck in the ground while teleporting
Hi I am new to Unity. I am making a project with a teleportation function like ender pearls in Minecraft. I used a game-object as a target, eg. -
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.up, distance, solidChecker);
if (hitInfo.collider != null)
{
if (hitInfo.collider.CompareTag("Ground"))
{
Debug.Log("Teleport");
tel = true;
telPoint.transform.position = transform.position;
}
else
tel = false;
DestroyProjectile();
}
And another script in the player -
public void boolTeleport(bool tel)
{
if (tel == true)
shouldTel = true;
else
shouldTel = false;
if (shouldTel == false)
tel = false;
}
private void Update()
{
if(shouldTel == true)
{
transform.position = telPoint.transform.position;
shouldTel = false;
}
}
}
So these two scripts have a GameObject variable -
public GameObject telPoint;
And in Unity, I added an empty object prefab as telPoint, as the projectile is a prefab, so I can't add an empty object directly.
Now, sometimes, if I throw the crystal on the ground and jump at the same time, I safely teleport above ground. Even without jumping I sometimes teleport above ground. But if I throw it at the side of a tile (of a tilemap) it teleports me inside the ground, where I can only move horizontally, and cannot jump or throw crystal outside. And if I throw it far away, it teleports me inside the ground almost always. What to do now?
I'm lost in what script it doesn't work?
How is this teleporting supposed to be?
I think I need a little bit bigger code to understand the codeflow at the raycast
I don't know Minecraft.
I think it should be like this:
telPoint.transform.position = hitInfo.position + Vector2.Up*distanceFromGround;
What is DinstanceFromGround, and how to use it?
Basically the problem is that the "position" of an object is usually its center, so by setting the position of an object to the ground, you're teleporting its bottom half into the ground, and by putting it onto the wall, you will almost certainly end up in the wall most of the time. This answer is trying to account for that by offsetting the point of teleport upwards a little before you teleport. It's not really the best solution but it's definitely the simplest, and if it works for your case, then there's no problem.