0
\$\begingroup\$

I don't understand why this doesn't work. The code only acts when I press "Horizontal" buttons.

Here's the code:

using UnityEngine;
using Flycer.Helpers;

namespace Flycer.Controllers
{
    public class MovementNew : BaseController
    {
        #region ========== Variables ========

        [SerializeField] [Tooltip("Forward moving speed")] [Range(0, 1f)] float _forSpeed = 0.5f;
        [SerializeField] [Tooltip("Slide speed")] private float speedSlide = 10;
        [SerializeField] [Tooltip("Max slide distance")] private float maxSlide = 4;

        private Vector3 _curPos;
        float slide = 0;
        int i = 1;

        #endregion ========== Variables ========

        #region ========== Unity-time ========

        private void Start()
        {
            base.On();
            _curPos = transform.position;
        }

        private void Update()
        {
            if (!Enabled)
                return;

            if (Input.GetButton(Controls.Horizontal.ToString()))
                Moving();
        }

        private void FixedUpdate()
        {
            _curPos += new Vector3(0, 0, _forSpeed);
        }

        #endregion ========== Unity-time ========

        #region ========== Methods ========

        void Moving()
        {
            slide = Input.GetAxis("Horizontal") * speedSlide;

            _curPos.x += slide * Time.deltaTime;

            _curPos.x = Mathf.Clamp(_curPos.x, -maxSlide, maxSlide);

            transform.position = _curPos;
        }

        #endregion ========== Methods ========
    }
}

It doesn't move in any condition whether it has a RigidBody or not.

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Your fixed update is only adding to the z-axis vector without ever applying it to the transform. Your movement function is taking the same vector and handles the x-axis part. All changes over time to z-axis are applied then as well. But if you never call movement - movement only gets called when you press the horizontal button), it just accumulates on z-axis without movement.

To fix it, just add the z-axis changes right away in your fixed update. This way they are independent from your horizontal movement.

private void FixedUpdate() {
    _curPos += new Vector3(0, 0, _forSpeed);
    transform.position = _curPos;
}
\$\endgroup\$
2
  • \$\begingroup\$ Dammit! Yes. It was so...easy! How can I...Thank you! :D \$\endgroup\$
    – Dead Lord
    Commented Feb 11, 2021 at 20:27
  • \$\begingroup\$ @DeadLord if the code is partially working (like you wrote only acts when I press "Horizontal" buttons) then the work is easy. Find out what is the difference between pressing the button and not pressing the button. \$\endgroup\$
    – Zibelas
    Commented Feb 12, 2021 at 6:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .