Search Unity

Control player while moving it in a direction

Discussion in 'Physics' started by lolman981234, May 23, 2020.

  1. lolman981234

    lolman981234

    Joined:
    May 22, 2020
    Posts:
    3
    I want to be able to control the player left right and jump while constantly moving it in a direction at a constant speed. Is there any way to do this? I've tried moving the player forward using AddForce(), but it moves faster over time.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,487
    Set the Rigidbody(2D) velocity directly in the axis of movement ensuring you don't alter the velocity in the "jump" direction. You can "jump" by setting the velocity in that direction or adding a force/impulse when you jump.
     
  3. lolman981234

    lolman981234

    Joined:
    May 22, 2020
    Posts:
    3
    I forgot to mention that I'm making a 3D project, sorry.
     
  4. pappalardodd

    pappalardodd

    Joined:
    Apr 13, 2020
    Posts:
    96
    If you just want to move left and right while going at constant speed, and you're not interested in physics. You can set the Rigidbody speed directly to a speed you want. leaving the Y axis free so as not to prevent the jump.

    Code (CSharp):
    1. Vector3 vel = rigidbody.velocity;
    2. vel.x = movement.x * speed;
    3. vel.z = movement.z * speed;
    4. rigidbody.velocity = vel;
     
  5. lolman981234

    lolman981234

    Joined:
    May 22, 2020
    Posts:
    3
    (sorry for replying late)

    I've tried your code and it didn't work, it generated an error: The name 'movement' does not exist in the current context
     
  6. pappalardodd

    pappalardodd

    Joined:
    Apr 13, 2020
    Posts:
    96
    sorry I used it for me in a project. movement is a vector used to describe the direction to make the object walk.
    I called my movement vector and updated it in Update like this:
    Code (CSharp):
    1. float Horizontal = Input.GetAxis("Horizontal");
    2. float Vertical = Input.GetAxis("Vertical");
    3. movement = (transform.right * Horizontal + transform.forward * Vertical);
    if you want to move based on how the camera is facing then use this:
    Code (CSharp):
    1. movement = (Camera.main.transform.right * Horizontal + Camera.main.transform.forward * Vertical);
    PS: speed is a float, you decide to indicate the speed at which the rigidbody moves