Home>

I want to move with Velocity

I was able to move horizontally using velocity, but it is fixed in the Y-axis direction. If possible, I would like to make it affected by gravity only in the y-axis direction, but what should I do?

Corresponding source code

C #
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement: MonoBehaviour
{
public float m_Speed;
private bool space = Input.GetKey ("Space");

Rigidbody2D m_rigidbody2D;

private void Start ()
{
m_rigidbody2D = GetComponent();
}
private void FixedUpdate ()
{
float horizontal = Input.GetAxis ("Horizontal");
float vertical = Input.GetAxis ("Vertical");

Vector2 m_Vector2 = new Vector2 (horizontal * m_Speed, 0f);

m_rigidbody2D.velocity = (m_Vector2);
}
}

Supplementary information (FW/tool version, etc.)

Version used: Unity2019.4.12f1 Personal

  • Answer # 1

    Vector2 m_Vector2 = new Vector2 (horizontal * m_Speed, 0f);
    m_rigidbody2D.velocity = (m_Vector2);

    Here, the acceleration of the Y axis is fixed at 0. The quickest way is to add the current acceleration.

    Vector2 m_Vector2 = new Vector2 (horizontal * m_Speed, m_rigidbody2D.velocity.y);
    m_rigidbody2D.velocity = (m_Vector2);

  • Answer # 2

    I have pasted a script that adds velocity to the top, bottom, left, and right with "W", "S", "D", and "A" on the keyboard. By the way, the movement by velocity is deprecated in Unity official, but it can be used because it does not cause bugs just because it moves unnaturally.
    Regarding the settings of the RigidBody component
    Use Gravity is on
    Is Kinematic is off
    Freeze Position and Freez Rotation of Constraints are all off
    Please keep it.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class Agent: MonoBehaviour
    public Rigidbody Rigid;
        // Start is called before the first frame update
        void Start ()
        {
            Rigid = GetComponent<Rigidbody>();
        }
        // Update is called once per frame
        void Update ()
        {
            Vector3 vel = Vector3.zero;
            if (Input.GetKeyDown (KeyCode.W))
            {
                vel.y + = 3;
                Rigid.velocity = vel;
            }
            else if (Input.GetKeyDown (KeyCode.S))
            {
                vel.y-= 3;
                Rigid.velocity = vel;
            }
            else if (Input.GetKeyDown (KeyCode.D))
            {
                vel.x + = 3;
                Rigid.velocity = vel;
            }
            else if (Input.GetKeyDown (KeyCode.A))
            {
                vel.x-= 3;
                Rigid.velocity = vel;
            }
        }
    }