Search Unity

How to move rigidbody at constant, unchanging velocity?

Discussion in 'Scripting' started by VileGoo, Oct 9, 2017.

  1. VileGoo

    VileGoo

    Joined:
    Apr 29, 2017
    Posts:
    220
    Hello!

    I am trying to get my player to move along the x global axis at a constant, unchanging speed so that if the player is moving up a ramp or down a slope the velocity will stay the same. The only time is should stop is when it hits a wall.

    The player can jump, and when he is jumping it will spin around until landing. The problem is, my current code doesn't seem to work and will fluctuate either slowing down or speeding up randomly after jumping/falling. The player will even end up sliding backwards for no reason.

    So I need my player to move along the x global axis at a constant velocity.

    Code (CSharp):
    1.     void FixedUpdate()
    2.     {
    3.         //Movement
    4.         rb.transform.Translate (Vector3.right * Time.deltaTime * speed, Space.World);
    5.  
    6.         //Jump
    7.         if (Input.GetMouseButtonDown(0) && (touchingSurface)) {
    8.             rb.AddForce (Vector3.up * jumpSpeed);
    9.         }
    10.     }
    I also put a physics material on the cube to remove any friction or bouncing.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Your current code basically teleports the player, which the physics engine is going to throw a fit over whenever it bumps into something. Rather than using Translate() just set the velocity directly.
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133