using System.Collections; using System.Collections.Generic; using UnityEngine; public…
- User
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MovingPlatform : MonoBehaviour { public float moveDistance = 10f; // Расстояние, на которое будет двигаться платформа public float moveSpeed = 3f; // Скорость движения платформы public float pauseDuration = 2f; // Промежуток времени для паузы между движениями public bool moveX = true; // Флаг, указывающий, разрешено ли движение по оси X public bool moveY = false; // Флаг, указывающий, разрешено ли движение по оси Y public bool moveZ = false; // Флаг, указывающий, разрешено ли движение по оси Z
csharp Copy code private Vector3 startPosition; // Начальная позиция платформы private Vector3 targetPosition; // Целевая позиция платформы
void Start() { startPosition = transform.position; Vector3 moveDirection = Vector3.zero; if (moveX) moveDirection += Vector3.right; if (moveY) moveDirection += Vector3.up; if (moveZ) moveDirection += Vector3.forward; targetPosition = startPosition + (moveDirection.normalized * moveDistance);
StartCoroutine(MovePlatform());}
IEnumerator MovePlatform() { while (true) { yield return StartCoroutine(MoveToTargetPosition()); yield return new WaitForSeconds(pauseDuration); yield return StartCoroutine(MoveToStartPosition()); yield return new WaitForSeconds(pauseDuration); } }
IEnumerator MoveToTargetPosition() { float elapsedTime = 0f; while (elapsedTime < moveSpeed) { float t = elapsedTime / moveSpeed; transform.position = Vector3.Lerp(startPosition, targetPosition, t); elapsedTime += Time.deltaTime; yield return null; } transform.position = targetPosition; }
IEnumerator MoveToStartPosition() { float elapsedTime = 0f; while (elapsedTime < moveSpeed) { float t = elapsedTime / moveSpeed; transform.position = Vector3.Lerp(targetPosition, startPosition, t); elapsedTime += Time.deltaTime; yield return null; } transform.position = startPosition; } } сделай что бы игрок используя character controller прилипал к платформе пока стоит на ней
- Assistant
Вот как вы можете изменить код, чтобы прилипание происходило, когда игрок стоит на платформе:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatform : MonoBehaviour { public float moveDistance = 10f; public float moveSpeed = 3f; public float pauseDuration = 2f; public bool moveX = true; public bool moveY = false; public bool moveZ = false; private Vector3 startPosition; private Vector3 targetPosition; private CharacterController characterController; private bool isPlayerOnPlatform = false; void Start() { startPosition = transform.position; Vector3 moveDirection = Vector3.zero; if (moveX) moveDirection += Vector3.right; if (moveY) moveDirection += Vector3.up; if (moveZ) moveDirection += Vector3.forward; targetPosition = startPosition + (moveDirection.normalized * moveDistance); characterController = GetComponent<CharacterController>(); StartCoroutine(MovePlatform()); } void FixedUpdate() { if (isPlayerOnPlatform) { characterController.Move(transform.position - startPosition); } } IEnumerator MovePlatform() { while (true) { yield return StartCoroutine(MoveToTargetPosition()); yield return new WaitForSeconds(pauseDuration); yield return StartCoroutine(MoveToStartPosition()); yield return new WaitForSeconds(pauseDuration); } } IEnumerator MoveToTargetPosition() { float elapsedTime = 0f; while (elapsedTime < moveSpeed) { float t = elapsedTime / moveSpeed; transform.position = Vector3.Lerp(startPosition, targetPosition, t); elapsedTime += Time.deltaTime; yield return null; } transform.position = targetPosition; } IEnumerator MoveToStartPosition() { float elapsedTime = 0f; while (elapsedTime < moveSpeed) { float t = elapsedTime / moveSpeed; transform.position = Vector3.Lerp(targetPosition, startPosition, t); elapsedTime += Time.deltaTime; yield return null; } transform.position = startPosition; } void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { isPlayerOnPlatform = true; } } void OnTriggerExit(Collider other) { if (other.CompareTag("Player")) { isPlayerOnPlatform = false; } } }Добавлены следующие изменения:
- Добавлена переменная
characterController, чтобы получить доступ к скрипту CharacterController игрока. - В методе
FixedUpdateдобавлено перемещение игрока с платформы, когда он находится на платформе. - Добавлены методы
OnTriggerEnterиOnTriggerExit, чтобы установить флагisPlayerOnPlatformв true/false при входе и выходе игрока с платформы.
- Добавлена переменная
- User
нужен скрипт при касании коллайдера перезапускает сцену, при нажатии на R перезагружает сцену
- Assistant
Для перезапуска сцены при касании коллайдера или при нажатии на клавишу R, вы можете использовать следующий скрипт:
using UnityEngine; using UnityEngine.SceneManagement; public class RestartScene : MonoBehaviour { void Update() { // Перезапуск сцены при нажатии на клавишу R if (Input.GetKeyDown(KeyCode.R)) { Restart(); } } void OnTriggerEnter(Collider other) { // Перезапуск сцены при касании коллайдера if (other.CompareTag("Player")) { Restart(); } } void Restart() { // Получение индекса текущей сцены int currentSceneIndex = SceneManager.GetActiveScene().buildIndex; // Загрузка текущей сцены SceneManager.LoadScene(currentSceneIndex); } }Добавленный скрипт проверяет нажатие клавиши R с помощью метода
Update(). Если клавиша R нажата, вызывается методRestart(), который перезапускает текущую сцену с помощьюSceneManager.LoadScene().Также добавлен метод
OnTriggerEnter(), который проверяет, когда другой объект с коллайдером соприкасается с коллайдером, к которому привязан данный скрипт. Если это игрок (other.CompareTag("Player")), сцена также перезапускается с помощью методаRestart(). Убедитесь, что у коллайдера, к которому привязан скрипт, есть тег "Player".