Hello, if the player does any action( for example press “E”). I want the player(RIgidBody) to teleport(not slide) a distance from the direction the camera is facing. I have tried( rb.transform.position += rb.transform.forward * distance ), But this teleports the player to a specific spot and not always striaght. That is why I need to somehow use the camera to say ff I turn 90 degrees and press “E” still telelport me stright and not to the right.
you can achieve this by using the Transform of both the camera and the player’s Rigidbody. The idea is to get the forward direction of the camera and use it to move the player in that direction. Here’s a simple script to achieve this:
using UnityEngine;
public class PlayerTeleport : MonoBehaviour
{
public float teleportDistance = 5f; // Adjust this value as needed
public Camera playerCamera;
public Rigidbody rb;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
TeleportPlayer();
}
}
void TeleportPlayer()
{
// Get the forward direction of the camera without considering the y-axis (vertical)
Vector3 cameraForward = playerCamera.transform.forward;
cameraForward.y = 0f; // Ignore vertical component
// Normalize the vector to ensure consistent movement speed in all directions
cameraForward.Normalize();
// Calculate the teleport destination
Vector3 teleportDestination = rb.transform.position + cameraForward * teleportDistance;
// Teleport the player to the destination
rb.MovePosition(teleportDestination);
}
}
This script listens for the “E” key press and then calculates the teleport destination based on the camera’s forward direction, ignoring the vertical component. The player is then moved to that destination using Rigidbody.MovePosition.
I hope this helps!