Home > Back-end >  Unity3d (C#) player won't teleport with new Vector3
Unity3d (C#) player won't teleport with new Vector3

Time:11-08

Whenever my player touches an object called "LevelEnd1" I want it to teleport the player to a specific set of coordinates and send a message to the console, but all my code does is send a message to the console. (there are no errors / I set the GameObject variable to the Player)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerTouched : MonoBehaviour
{
    public GameObject Player;

    public void OnControllerColliderHit(ControllerColliderHit collision)
    {
        if (collision.gameObject.tag == "LevelEnd1")
        {
            Player.transform.position = new Vector3(-193.5f, 5.860001f, 803.13f);
            Debug.Log("it worked!!");
        }
    }
}

CodePudding user response:

The problem was that my movement script was constantly changing my position, so I disabled my player's movement for 0.1 seconds before teleporting.

Player Touched code:

public void OnControllerColliderHit(ControllerColliderHit collision)
    {
        if (collision.gameObject.tag == "LevelEnd1")
        {
            StartCoroutine("Teleport");
        }
    }

    IEnumerator Teleport()
    {
        playerMovement.disabled = true;
        yield return new WaitForSeconds(0.1f);
        Player.transform.position = new Vector3(-193.5f, 5.860001f, 803.13f);
        Debug.Log("it worked!!");
        yield return new WaitForSeconds(0.1f);
        playerMovement.disabled = false;
    }

Player Movement code:

public bool disabled = false;

    Vector3 velocity;
    bool isGrounded;

    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if (isGrounded && velocity.y < 0 && !disabled)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x   transform.forward * z;

        if (move.magnitude > 1 && !disabled)
            move /= move.magnitude;

        controller.Move(move * speed * Time.deltaTime);

        velocity.y  = gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
  • Related