I’m sorry if this is a re-post but I have looked through the forums and have been unable to find a solution to my problem. I am trying to restrict an object to move only in the X-Y plane, as the game is a simple 2D scrolling. I have attached a Rigidbody component and the object moves from the left edge of the screen to the right, with a hidden cube placed in the centre to stop it passing off screen. The input is from the mouse not the keyboard.
I have modified a script I found on the wiki site
function FixedUpdate ()
{
// Get the input and set variables for it
horizontal = -Input.GetAxis("Mouse X");
vertical = Input.GetAxis("Mouse Y");
horizontal *= force;
vertical *= force;
if(rigidbody.velocity.magnitude < maxspeed))
{
//cancel out the forces in the Z direction
// * It is relative to the camera
// * we remove the z component because we really want to apply forces only on the 2D plane
var up = transform.TransformDirection(Vector3.up);
up.z = 0;
rigidbody.AddForce (up * vertical);
var right = transform.TransformDirection(Vector3.right);
right.z = 0;
rigidbody.AddForce (right * horizontal);
Debug.Log(transform.rotation);
}
}
When I check the transform using the debug I can still see values in the Z axis. A quick fix was to modify the Camera Mouselook C# script, clamp the rotation of my Rigidbody object. But the movement is somewhat jerky as I’m sure the two scripts are fighting each other…
We had a pretty good experience using a ConfigurableJoint attached to each object that should only move in two dimensions - just need to attach the component, set ZMotion to “Locked,” and then AngularXMotion and AngularYMotion to “Locked” as well (since we also only wanted rotations about the z axis.
I’m trying to do something similar but having issues.
I’m trying to allow an object to rotate in all three dimensions but not move along the z plane. I borrowed some of the code here as I was also getting jerking motion previously.
How can I throw out movement along one plane but allow all the other physics to continue?