Search Unity

How to smoothly move a RigidBody a fixed distance on Keydown

Discussion in 'Scripting' started by LostRelicGames, Jul 23, 2014.

  1. LostRelicGames

    LostRelicGames

    Joined:
    Aug 11, 2013
    Posts:
    34
    I'm trying to build a 3 lane runner with similar mechanics to Subway Surfer.

    Using c# what is the technique I could use to move the player smoothly from one lane to the next?
    I have a RigidBody attached to my player so I am of the understanding that I need to use AddForce().

    Currently I am doing something like this.
    Code (CSharp):
    1.     void Update() {
    2.         if (Input.GetKey("left"))
    3.             rigidbody.AddForce(15, 0, 0);
    4.        
    5.         if (Input.GetKey("right"))
    6.             rigidbody.AddForce(-15, 0, 0);
    7.        
    8.     }
    In psuedo code I'm trying to do :

    IF key pressed, THEN move player 5 units along the X axis.

    Any suggestions?
    Thanks
     
  2. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
  3. LostRelicGames

    LostRelicGames

    Joined:
    Aug 11, 2013
    Posts:
    34
    Thanks LightStriker, MovePosition proved to be a much better approach.
    And to answer my opening question about movement. I found the iTween library to be useful.
     
  4. Madhu04

    Madhu04

    Joined:
    Feb 25, 2019
    Posts:
    1
    Hi, this video tutorial will answer your question.