How to move a tank?

Hello,

I have a sort of commando game. I have a tank with a rigidbody and a box collider. I want the tank to move at a constant speed and I want that nothing moves the tank from its moving direction.

I tried to move it with rigidbody.AddRelativeForce as follows, but when it collides with another rigidbody, it “slides” from the collision point. If I increase the drag value, I can’t move the rigidbody ig I don’t increase the acceleration, but the slide problem does not disappear.

Code is:

var maxSpeed : float = 1.1;
var accel : float = 100000.0;

function FixedUpdate () {

	if(rigidbody.velocity.magnitude <= maxSpeed) {
		rigidbody.AddRelativeForce(Vector3.forward*accel);
	}

}

With Mass 10000 and Drag 10 it moves OK, but when collides, it slides.

I tried also with rigidbody.velocity but no way. As I increase the drag value I cannot move the rigidbody.

Any solution for this problem. I am sure I am doing something wrong, but I can’t see what.

Thank you!

Edit: Here’s what I found worked…

26854-jointconfig.png

  • Rotation is locked on the Y axis, so collisions can’t turn the tank to the side
  • A configurable joint is added with no Connected Body (which means it connects to the world)
  • You can ignore the “Connected anchor” - that will be auto-configured for you
  • Set XMotion to Locked and the others to Free
  • The rest of the settings you can leave at their default values.

This will keep the object locked in its current YZ plane. If you need to rotate the object, manually adjust the connected anchor like so beforehand to keep the joint from freaking out:

ConfigurableJoint joint = GetComponent<ConfigurableJoint>();
joint.connectedAnchor = transform.TransformPoint(joint.anchor);

26856-tanksjoint.gif

/End Edit - below are the original suggestions


You can try to cancel-out sideways movement: (this didn’t work)

Vector3 sidewaysVelocity = Vector3.Dot(rigidbody.velocity, transform.right) * transform.right;

rigidbody.AddForce(-sidewaysVelocity, ForceMode.VelocityChange);

I’m not sure whether it would suffice to do this every FixedUpdate, or if you might need to do this in OnCollisionEnter/Stay/Exit to override velocity changes during collisions.

Another option would be to use a ConfigurableJoint to constrain the tank to the world coordinate space, allowing free movement in the local YZ plane but not X. Not sure how well that would play with turning the tank though.