Good Scripting habits?

Hello there!

This is my second day with Unity, already in love with the powerful API.

So I’m trying to roll a cylinder upon User’s input, is it a good way to do this?
Or is there some optimized way??
Also, the rotation (left and right arrow key inputs) don’t seem to work…am i doing something wrong??

also, please direct me to some good tutorials to understand API of unity and some books(preferable)

PS. Excuse my English :slight_smile:

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    float torque = 100f;
    public Rigidbody rb;
    public Vector3 eulerAngleVelocity;

    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody>();


    }
   
    // Update is called once per frame
    void FixedUpdate () {
        if (Input.GetKey (KeyCode.UpArrow)) {

            rb.AddTorque(transform.up * torque );
        }
        if (Input.GetKey (KeyCode.DownArrow)) {

            rb.AddTorque (transform.up * -torque);
        }
        /*if (Input.GetKey (KeyCode.LeftArrow)) {

            Quaternion deltaRotation = Quaternion.Euler (eulerAngleVelocity * Time.deltaTime);
            rb.MoveRotation (rb.rotation * deltaRotation);
        }
        if (Input.GetKey (KeyCode.RightArrow)) {

            Quaternion deltaRotation = Quaternion.Euler (eulerAngleVelocity * Time.deltaTime);
            rb.MoveRotation (rb.rotation * deltaRotation);
        }*/
    }
}

Wrong function. Update is called once per frame, but FixedUpdate can be called multiple times per frame or even once every few frames. It’s dependent on the physics subsystem and should only be used for physics.

Well, to be fair, he is using physics here. Which is certainly the hard way to do it — I don’t recommend jumping right into physics as a beginner. Instead, remove the Rigidbody from your cylinder, and move it around by directly manipulating the Transform. (And then you should do this in Update, just as @Ryiah said.)

The reason I’m using physics here is, the cylinder should translate upon rotation (Rolling) and transform would no way do that(I guess it just rotates at fixed point?). My idea was to use 4 of these cylinder as wheels, for eg: in a car. Any how, ill try to look at Transform class too.

Unity gave me a template for script consisting Start() and Update() with those comments
I added ‘Fixed’ as I was experimenting with physics, but didn’t remove the comments :stuck_out_tongue:

You can AddForce to the rigidbody. This is like nudging it, and friction will make it roll. If you want to roll it and have that drive the cylinder, that should be legitimate as well. Try a sphere first to make sure you are not pushing along the wrong axis.