Search Unity

continuous bumping into wall

Discussion in 'Scripting' started by Kamelot89, Sep 28, 2016.

  1. Kamelot89

    Kamelot89

    Joined:
    Sep 20, 2016
    Posts:
    11
    I am using the following code to move my obejct with a rigid body around:

    Code (CSharp):
    1. public class Movement : MonoBehaviour {
    2.  
    3.     public float rotSpeed;
    4.     public float playerSpeed;
    5.  
    6.     void Update()
    7.  
    8.  
    9.     {
    10.         if (Input.GetKey (KeyCode.D))
    11.      
    12.         {
    13.             transform.Rotate (Vector3.up, Time.deltaTime * rotSpeed);
    14.         }
    15.  
    16.         else if (Input.GetKey (KeyCode.A))
    17.      
    18.         {
    19.             transform.Rotate (-Vector3.up, Time.deltaTime * rotSpeed);
    20.         }
    21.  
    22.         if (Input.GetKey (KeyCode.W))
    23.      
    24.         {
    25.             transform.Translate (Vector3.forward * Time.deltaTime * playerSpeed);
    26.             {
    27.                 if (Input.GetKey(KeyCode.LeftShift))
    28.                 transform.Translate (Vector3.forward * Time.deltaTime * playerSpeed * 2);  
    29.             }
    30.         }
    31.  
    32.         else if (Input.GetKey (KeyCode.S))
    33.      
    34.         {
    35.             transform.Translate (-Vector3.forward * Time.deltaTime * playerSpeed);
    36.  
    37.         }
    38.     }
    39. }
    How do I have to change the script to make the object not bumping continuously while moving into a collider? It should look like the default fpscontroller.
     
  2. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    The suggestion I see often made, and am myself making, is that if you have a rigid body, apply forces to the rigid body rather than change the transform translate.
    I'm not certain I understand the behavior you're getting, but I think I do and it's probably because the object is partially entering the collider, then physics takes over and the object get's pushed out.
     
  3. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
  4. Vedrit

    Vedrit

    Joined:
    Feb 8, 2013
    Posts:
    514
    or rigidbody.Velocity
     
    RavenOfCode likes this.
  5. RavenOfCode

    RavenOfCode

    Joined:
    Apr 5, 2015
    Posts:
    869
    Or rigidbody.AddForce. Though for his purpose of making it look like the default fps controller rb.MovePosition is probably the most accurate option.