Hello.
I have problem with writing move scrpit for player character which is sphere.
I want to move it independently from global orientation and independently from sphere transform.
Let me give an example:
If I use AddRelativeTorque/Force sphere`s transform will be rotating and because of that It will be impossible to move it anymore. If I bind “W” to move forward and then press it, sphere might roll in left direction or sth like that.
If I use AddTorque I will be only able to move along global axes, so it is impossible to turn back with only 2 keys (“W” + “D” for example)
I tried to experiment with empty gameobject which contain sphere. I thought I can move sphere with adding force to empty object and then rotate object with velocity (transform.rotation.SetLookRotation()) but still no results.
My last script is very close to my idea, but there is 2 problems. 1. Rotation for X and Z axes must be frozen. 2. Game object don`t rotate with velocity, when I rotate it manually it works as I want.
public class move_character : MonoBehaviour
{
public float speed = 1f;
private Rigidbody rb;
private Vector3 torque_vector_x = new Vector3(1, 0, 0);
private Vector3 torque_vector_z = new Vector3(0, 0, 1);
private void move_forward()
{
rb.AddRelativeForce(torque_vector_x * speed * Time.deltaTime);
}
private void move_back()
{
rb.AddRelativeForce(torque_vector_x * speed * Time.deltaTime * (-1));
}
private void move_left()
{
rb.AddRelativeForce(torque_vector_z * speed * Time.deltaTime);
}
private void move_right()
{
rb.AddRelativeForce(torque_vector_z * speed * Time.deltaTime * (-1));
}
void Start()
{
rb = gameObject.GetComponent<Rigidbody>();
}
void Update()
{
transform.rotation.SetLookRotation(rb.velocity);
if (Input.GetKey(KeyCode.W))
{
move_forward();
}
if (Input.GetKey(KeyCode.S))
{
move_back();
}
if (Input.GetKey(KeyCode.A))
{
move_left();
}
if (Input.GetKey(KeyCode.D))
{
move_right();
}
}
}
Anyone has any idea how can I make this ball moving as I described?