Search Unity

Moving my object

Discussion in 'Scripting' started by SonicWave, Jan 9, 2014.

  1. SonicWave

    SonicWave

    Joined:
    Jan 9, 2014
    Posts:
    4
    Hello, I have been trying to get my object (a cube) to move forward, left, and right for a while. It has a rigid body. This is what I have been using. (Csharp)

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Rigidbodymovement : MonoBehaviour {
    5.  
    6.     public float move = 0f;
    7.     public float turn = 0f;
    8.  
    9.     // Update is called once per frame
    10.     void Update () {
    11.     if (Input.GetKey (KeyCode.W))
    12.             rigidbody.AddRelativeForce (Vector3.forward * move, ForceMode.Acceleration);
    13.  
    14.  
    15.  
    16.     if (Input.GetKey (KeyCode.D))
    17.             rigidbody.AddTorque(Vector3.up * turn, ForceMode.Acceleration);
    18.  
    19.     if (Input.GetKey (KeyCode.A))
    20.             rigidbody.AddTorque(Vector3.up * -turn, ForceMode.Acceleration);
    21.  
    22.         }
    23. }
    24.  
    This works, HOWEVER, it will start to rotate because of friction and start bouncing all over the place. Is there anyway to make it so it will slide forward instead of moving like a wheel rotating forward?

    Thanks,

    SonicWave
     
  2. deadfire52

    deadfire52

    Joined:
    Jun 15, 2011
    Posts:
    101
    In the rigidbody properties in the Inspector, there are checkboxes for Freeze Rotation, select those are you should be good.
     
  3. SonicWave

    SonicWave

    Joined:
    Jan 9, 2014
    Posts:
    4
    I tried that, it worked. However, it is very unsmooth. Is their a way I can make it look smooth. And it is also moving to the right (slightly) when I move, Why would that be?

    EDIT: When I run it straight, it starts to rotate to the right
     
  4. deadfire52

    deadfire52

    Joined:
    Jun 15, 2011
    Posts:
    101
    Instead of using rigidbody.add force to move the object, try simply adding to the gameObject's transform.position.
     
  5. SonicWave

    SonicWave

    Joined:
    Jan 9, 2014
    Posts:
    4
    So how would I add this to my person. How would I use transform.position in this context? (Sorry, I am very new to unity. Thanks for helping me btw)
     
  6. SomeOnePickedMyNose

    SomeOnePickedMyNose

    Joined:
    Jan 10, 2014
    Posts:
    7
  7. SonicWave

    SonicWave

    Joined:
    Jan 9, 2014
    Posts:
    4
    Thanks very much!!! That helped me a lot!