Triborg-333
@Triborg-333

Плавное движение и вращение персонажа с помощью acceleration.x?

Здравствуйте, есть игра по типу: "Doodle Jump", как реализовать плавное движение и вращение персонажа при повороте экрана. (acceleration) он резко поворачивается. Я не знаю как решить эту проблему

62969d837954c704925262.png

private AudioSource audioJump;
    public static Rigidbody2D rb;
    private float moveInput;

    Vector2 move = Vector2.zero;
    public float speed;
    public float jumpForce;
    public GameObject jumpEffect;

    public static bool isFly = false;
    private bool faceRight = false;
    public static bool gameOver = false;

    public GameObject GameOver_Menu;

    private int sprite_index;
    public Sprite[] sprite;

    private Vector3 Player_LocalScale;

    private float lowPassValue;

void Update()
    {
        if (gameOver == true || SceneManager.GetActiveScene().buildIndex == 0) return;
        
        if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
        {
            moveInput = Input.acceleration.x * speed;
        }
        else
        {
            moveInput = Input.GetAxis("Horizontal") * speed;
        }


        if (faceRight == true && moveInput > 0.3f)
        {
            Flip();
        }
        else if (faceRight == false && moveInput < -0.3f)
        {
            Flip();
        }
    }

    private void FixedUpdate()
    {
        move = rb.velocity;
        if (isFly)
        {
            move.x = moveInput;
            move.y = JetPack.speed;
        }
        else
        {
            move.x = moveInput;
            move.y = rb.velocity.y;
        }


        if (move.y < 0)
        {
            GetComponent<BoxCollider2D>().enabled = true;
        }
        else
        {
            GetComponent<BoxCollider2D>().enabled = false;
        }
        rb.velocity = move;

        Vector3 wrap = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0));
        float Offset = 0.5f;

        if (transform.position.x > -wrap.x + Offset)
            transform.position = new Vector3(wrap.x - Offset, transform.position.y, transform.position.z);
        else if (transform.position.x < wrap.x - Offset)
            transform.position = new Vector3(-wrap.x + Offset, transform.position.y, transform.position.z);
    }
   private void Flip()
    {
        faceRight = !faceRight;
        Vector2 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
  • Вопрос задан
  • 77 просмотров
Решения вопроса 1
K0TlK
@K0TlK
Буллю людей.
Код твой изменять не буду, сам все перепишешь на моем примере.

Начнем с низов. Есть ввод от игрока. Для этого ввода вводим интерфейс:
namespace SmoothMovement
{
    public interface IPlayerInput
    {
        float Acceleration { get; }
    }
}


Далее нам нужно сглаживать этот Acceleration, значит вводим еще один интерфейс:
namespace SmoothMovement
{
    public interface ISmoothAcceleration
    {
        float Smooth(float acceleration, float input);
    }
}


Далее реализуем IPlayerInput:
using UnityEngine;

namespace SmoothMovement
{
    public class MobileInput : MonoBehaviour, IPlayerInput
    {
        public float Acceleration { get; private set; }

        [SerializeField] private float _minAcceleration = -1f;
        [SerializeField] private float _maxAcceleration = 1f;
        [SerializeField] private float _smoothMultiplier = 5f;
        [Range(0, 1)] [SerializeField] private float _fadingSpeed = 0.01f;

        private ISmoothAcceleration _smoothing;

        private void Awake()
        {
            _smoothing = new SmoothedAcceleration(_minAcceleration, _maxAcceleration, _smoothMultiplier, _fadingSpeed);
        }

        private void Update()
        {
            Acceleration = _smoothing.Smooth(Acceleration, Input.acceleration.x);
        }
    }
}


В апдейте присваиваем свойству Acceleration сглаженное значение инпута. Далее само сглаживание:
using UnityEngine;

namespace SmoothMovement
{
    public class SmoothedAcceleration : ISmoothAcceleration
    {
        private readonly float _multiplier;
        private readonly float _minValue;
        private readonly float _maxValue;
        private readonly float _fadingSpeed;

        
        public SmoothedAcceleration(float minValue, float maxValue, float multiplier, float fadeSpeed)
        {
            _minValue = minValue;
            _maxValue = maxValue;
            _multiplier = multiplier;
            _fadingSpeed = fadeSpeed;
        }
        
        public float Smooth(float acceleration, float input)
        {
            if (input == 0)
            {
                acceleration = Mathf.Lerp(acceleration, 0, _fadingSpeed);
                return acceleration;
            }
            
            acceleration += input * _multiplier * Time.deltaTime;
            acceleration = Mathf.Clamp(acceleration, _minValue, _maxValue);

            return acceleration;
        }
    }
}


Есть минимальные и максимальное значение ускорения, множитель - чем он больше, тем быстрее разгоняться будет и скорость затухания ускорения - чем больше тем быстрее ускорение будет стремиться к нулю. И тест:
using UnityEngine;

namespace SmoothMovement
{
    public class TestMovement : MonoBehaviour
    {
        [SerializeField] private MonoBehaviour _input = null;
        [SerializeField] private float _speed = 10f;
        
        
        private IPlayerInput Input => (IPlayerInput)_input;


        private void OnValidate()
        {
            if (_input is IPlayerInput) return;
            
            Debug.LogError($"{nameof(_input)} should implement {nameof(IPlayerInput)}");
            _input = null;
        }

        private void FixedUpdate()
        {
            Move(Input.Acceleration);
        }

        private void Move(float direction)
        {
            if (direction == 0) return;
            
            var position = transform.position;
            position.x += direction * _speed * Time.deltaTime;
            transform.position = position;
        }
    }
}

Инжектим IPlayerInput через инспектор, двигаем геймобжект. С вращением делай сам что-нибудь, я не знаю как у тебя там что должно вращаться
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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