Elezthem
@Elezthem
Full Stack Developer

Как сделать чтобы квадратик поворачивался во время прыжка?

Я делаю свою пародию на Гд, вот значит что квадратик там поворачивается во время прыжка, я хочу чтобы у меня было также, вот ниже весь мой код игрока Player, вчера ломал голову и есть 1 скрипт, но тот скрипт работал через ж*пу, по другому я не знаю, надеюсь что кто-то поможет мне с этой задачей.

Код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    private const float Speed = 6;
    private const float JumpForce = 7;
    private const float BackgroundSpeed = 1;  // Скорость фона
    [SerializeField] private Rigidbody2D rigidbody2D;
    [SerializeField] private ParticleSystem particleSystem;
    [SerializeField] private AudioSource audioSource;
    private bool _isGrounded;

    [SerializeField] private Transform groundCheckObject;
    [SerializeField] private LayerMask layerMask;
    [SerializeField] private Transform bg;
    [SerializeField] private GameObject DeadSong;
    private float initialBgPositionX;  // Начальная позиция фона

    private Vector3 initialPosition;  // Добавляем переменную для хранения начальной позиции

    private void Start()
    {
        initialPosition = transform.position;  // Сохраняем начальную позицию при запуске сцены
        initialBgPositionX = bg.position.x;
    }

    private void Update()
    {
        if (!Global.Playmode) return;
        _isGrounded = Physics2D.OverlapCircle(groundCheckObject.position, 0.1f, layerMask);

        if (_isGrounded)
        {
            particleSystem.Play();
        }
        else
        {
            particleSystem.Stop();
        }

        transform.Translate(new Vector2(Speed * Time.deltaTime, 0));
        // Двигаем фон с меньшей скоростью
        float bgMove = Speed * BackgroundSpeed * Time.deltaTime;
        bg.Translate(new Vector2(bgMove, 0));

        Jump();

        ParticleSystemSetSpeed();
    }

    private void ParticleSystemSetSpeed()
    {
        var velocityOverLifeTime = particleSystem.velocityOverLifetime;
        velocityOverLifeTime.x = rigidbody2D.velocity.x;
    }

    private void Jump()
    {
        if (Input.GetMouseButtonDown(0) && _isGrounded)
        {
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, JumpForce);

        }
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Obstacle"))
        {
            DieAndRespawn();
            audioSource.Play();
            Invoke("HideDeadSong", 0.1f);
        }
    }

    private void DieAndRespawn()
    {
        transform.position = initialPosition;

        bg.position = new Vector3(initialBgPositionX, bg.position.y, bg.position.z);
        DeadSong.SetActive(false);
    }

    private void HideDeadSong()
    {
        // Инвертируем состояние активности объекта DeadSong
        DeadSong.SetActive(!DeadSong.activeSelf);
    }
}


Суть: Чтобы квадратик поворачивался во время прыжка как в оригинальной Гд.
  • Вопрос задан
  • 354 просмотра
Решения вопроса 2
Примерно так (возможно надо будет поправить немного):
float jumpStartRotation = 0;
private void Jump()
    {
        if (Input.GetMouseButtonDown(0) && _isGrounded)
        {
            rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, JumpForce);
            jumpStartRotation = transform.rotation.z;
        }
    }
...
if(!_isGrounded)
{
   float deltaAngle = Math.Clamp(x * deltaTime, 0, jumpStartRotation + 90); //чтобы не более 90 град
    transform.rotation.z = jumpStartRotation  + deltaAngle;
}

где x = надо вручную подобрать, чтобы успело оборот сделать когда прыжок на платформу повыше.
Ответ написан
Elezthem
@Elezthem Автор вопроса
Full Stack Developer
Вот самый простой код
using UnityEngine;
using System.Collections;

public class SquareController : MonoBehaviour
{
    public float rotationAmount = 90.0f;
    

    private bool isRotating = false;

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && !isRotating)
        {
            isRotating = true;
            RotateCube();
        }
    }

    void RotateCube()
    {
        float targetAngle = transform.eulerAngles.z + rotationAmount;
        Quaternion targetRotation = Quaternion.Euler(0, 0, targetAngle);

        StartCoroutine(RotateCoroutine(targetRotation));
    }

    System.Collections.IEnumerator RotateCoroutine(Quaternion targetRotation)
    {
        float duration = 0.5f;

        Quaternion startRotation = transform.rotation;
        float time = 0.0f;

        while (time < duration)
        {
            transform.rotation = Quaternion.Lerp(startRotation, targetRotation, time / duration);
            time += Time.deltaTime;
            yield return null;
        }

        transform.rotation = targetRotation;
        isRotating = false;
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы