# Rotate GameObject based on RigidBody Velocity

Hello,

Just wondering if someone would be kind enough to help me work something out (in C# preferably).

Basically I have a cube with a little propeller on the top of it. The cube has a Rigidbody and is controlled by keys (for forwards/backwards motion). I am trying to work out how to make the propeller rotate (clockwise/anti-clockwise on Y axis) based on the RigidBody’s Velocity.

Ideally I am wanting to be able to drag the object with the RigidBody component and the propellor GameObject onto the script in the inspector.

I have a ‘faked’ solution where it rotates the propellor based on key input and a float for rotation speed but as soon as I am not holding down a key it stops rotating so it looks a bit silly to see the cube slowing down and the propellor has already stopped rotating.

Any help would be very much appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

``````public class PlayerRotObject : MonoBehaviour
{

// SPEED = DISTANCE / TIME

public Vector3 localV;

public float RBVelo;

public GameObject thisObject; 	// Object with Rigidbody
public GameObject leftProp;		// Left Propellor Object
public GameObject rightProp;	// Right Propellor Object
private Rigidbody thisRB;

Vector3 currentPosition;

// Use this for initialization
void Start ()
{

thisRB = thisObject.GetComponent<Rigidbody>();

}

// Update is called once per frame
void Update ()
{
RBVelo = thisRB.velocity.magnitude;

Vector3 localVelocity = transform.InverseTransformDirection( thisRB.velocity );
// Just to visualize in the inspector
localV = localVelocity;

float dir_mult = 1; // Determine direction to "spin" the wheel; 1 is forward, -1 is backward
if(localVelocity.z < 0) dir_mult = -1;

// Magnitude * time.deltaTime is basically the "distance" the rb traveled
//  So, we need to figure out how much to "spin" the wheels...
// this ONLY takes into account SPEED, not DIRECTION.  So, if hte car is moving backwards,
// we'd need to actually multiply by -1
float degRot = ( (RBVelo * Time.deltaTime) / WheelRadius) * Mathf.Rad2Deg * dir_mult;
leftProp.transform.Rotate( degRot, 0, 0 );
rightProp.transform.Rotate( degRot, 0, 0 );

}
}
``````