Untitled
unknown
plain_text
a year ago
3.2 kB
4
Indexable
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class Selection : MonoBehaviour { public float teleportDistance = 100f; // Distance to teleport the player public float teleportSpeed = 1f; // Speed of teleportation private GameObject highlightedCube; // Store the highlighted cube GameObject void Update() { // Check if the user's cursor is on the cube CheckForHighlightedCube(); // Check if the "E" key is pressed and the cursor is on a cube if (Input.GetKeyDown(KeyCode.E)) { TeleportPlayerToCube(); } } void CheckForHighlightedCube() { // Create a ray from the camera's position and forward direction Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; // Declare a variable to hold information about the hit // Cast the ray into the scene and check for intersection if (Physics.Raycast(ray, out hit)) { GameObject hitObject = hit.collider.gameObject; // Check if the hit object is a cube if (hitObject.CompareTag("Cube")) { // Highlight the cube (change its color to red) HighlightCube(hitObject); } else { // If the cursor is not on a cube, remove highlight RemoveHighlight(); } } else { // If the cursor is not over anything, remove highlight RemoveHighlight(); } } void HighlightCube(GameObject cube) { // Change the cube's material color to red Renderer cubeRenderer = cube.GetComponent<Renderer>(); cubeRenderer.material.color = Color.red; // Store the highlighted cube GameObject highlightedCube = cube; } void RemoveHighlight() { // Check if there's a highlighted cube if (highlightedCube != null) { // Restore the original material color of the highlighted cube Renderer cubeRenderer = highlightedCube.GetComponent<Renderer>(); cubeRenderer.material.color = Color.white; // Reset the highlighted cube GameObject reference highlightedCube = null; } } void TeleportPlayerToCube() { // Check if there is a highlighted cube to teleport to if (highlightedCube != null) { // Teleport the player to the position of the highlighted cube GameObject player = GameObject.Find("Player"); if (player != null) // Ensure player GameObject was found { Vector3 teleportPosition = highlightedCube.transform.position + highlightedCube.transform.up * teleportDistance; player.transform.position = teleportPosition; } else { Debug.LogError("Player GameObject not found!"); } } else { Debug.LogError("No highlighted cube to teleport to!"); } } }
Editor is loading...
Leave a Comment