2
\$\begingroup\$

I am trying to move a cube with my keyboard on a plane surface. However, the cube always rolling instead of moving. How could I slide the cube on the plane?

What I have done:

  • I added a plane game object with a mesh colider
  • I added a 3D cube object with a box colider and rigidbody
  • I appended a ControllerScript to the cube

ControllerScript

private const float Speed = 10;

private Rigidbody rb;

void Start()
{
    this.rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    var x = Input.GetAxis("Horizontal");
    var z = Input.GetAxis("Vertical");

    this.rb.AddForce(Speed * x, 0, Speed * z);
}

It looks like the AddForce method upset the cube. I already tried to reduce the friction of the plane and the cube, but this only delays the problem.

How could I move the cube without rolling it? Whats the common way to do it?

\$\endgroup\$
  • \$\begingroup\$ try this answers.unity3d.com/questions/120956/… \$\endgroup\$ – nikoliazekter Apr 27 '15 at 17:55
  • \$\begingroup\$ Could I merge the meshes of a simple cube? I tried AddForceAtPosition, but it creates a similar behavior. The cube gets upset if I push the button too long. \$\endgroup\$ – user44250 Apr 27 '15 at 18:34
  • \$\begingroup\$ Can't you just constrain certain rotation axis on the rigidbody? \$\endgroup\$ – Savlon Apr 27 '15 at 21:06
2
\$\begingroup\$

Add the following line to your Start() method:

GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ;

This will prevent the object from rotating on x & z axis, which will prevent it from rolling. If you don't want it to turn sideways as well, add FreezeRotationY as well, and then it will not rotate at all but only move:

GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationY;

If at any point you wish for it to be able to roll, for any reason, you can re enable the rotation by using:

GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
\$\endgroup\$
1
\$\begingroup\$

You can

  • Freeze the rotation
  • Change the transform's position(with translate, not recommended for physics though)
  • Set the rotation equal to itself
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy