Player not teleporting from object to empty object

Viewed 48

I assigned teleportation target and the player to an object from where I want to be teleported. But it is not working at all, as in other examples players have RigidBody properties, on the other hand I don't have RigidBody in my NavMesh. Is this maybe an issue? I'm trying something like this:

private void OnTriggerEnter(Collider other)
{
    thePlayer.transform.position = teleportTarget.transform.position;
}

This is my movement code:

public class Player : MonoBehaviour
{
    [SerializeField]
    private GameObject cameraPrefab;

    private PlayerMovement playerMovement;

    void Awake()
    {
        GameObject camera = Instantiate(cameraPrefab);
        camera.GetComponent<PlayerCamera>().target = transform;

        playerMovement = GetComponent<PlayerMovement>();
        playerMovement.cam = camera.GetComponentInChildren<Camera>();
    }
}

Any idea to fix this?

1 Answers

To teleport a GameObject to some other GameObject you can do this:

  1. Create player, teleporter, and teleporterExit
  2. Add components to them: player -Rrigidbody, Collider teleporter - Collider YOU HAVE TO CHANGE ITS "Is trigger" PROPERTY TO TRUE

teleportExit - can be empty

  1. Add this class to your teleporter as a component
     public class TeleporterBehavior : MonoBehaviour
    {
        public GameObject TeleporterExit;
        private void OnTriggerEnter2D(Collider2D collision)
        {
            collision.gameObject.transform.position = TeleporterExit.transform.position;
        }
    }
  1. Add some movement to your player
public class PlayerController : MonoBehaviour
{
    public float Force;
    Rigidbody2D rb;
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    private void FixedUpdate()
    {
        rb.AddForce(new Vector2(Force, 0f));
    }
}
  1. Put the objects in the scene so that they can interact which each other enter image description here

  2. Observe how the player teleports itself after touching teleporter.

Related