1
\$\begingroup\$

I'm trying to create an infinite flying game where the gameobject (a plane) keeps moving forward and at a particular height throughout the game. I want to be able to
roll and pitch the plane but not move it up/down. I added a rigid body to the plane and selected "y" position constrain. However the plane doesn't stay in the 'y' position but starts move up or down. I just have a script that translates the plane in the z direction. Not sure how to implement the mobile input and keep at the same "y" position throughout.

Update

Here is the code for the plane. Its very basic as I'm not sure how to use the accelerometer:

public class Player : MonoBehaviour {

public float speed = 1.0f;

void Update () {
    float tempx = Input.acceleration.x;
    float tempy = Input.acceleration.y;
    float tempz = Input.acceleration.z;
    transform.Translate(0, 0, 10); // move forward in z 
    transform.Rotate( 0,  tempy * speed, tempz * speed);
}

As for the freezing of the 'y' position, I'm just selecting the y constraint available in the inspector that comes along with the rigidbody.

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

When in doubt, be sure to read the documentation for the methods you're using.

Here you'll find out that if you give transform.Translate three float parameters and no Space, it defaults to translating in local coordinates. ie. in this case, it moves along the object's Z axis, not the world's Z axis.

Once you rotate the plane, that direction might point up or down, changing the global y coordinate of the object.

Because this change is going through the Transform, it completely bypasses the constraints you imposed on the Rigidbody.

So, possible fixes:

  • Specify Space.World if you want to move forward in world space, not local space

    transform.Translate(0, 0, translationSpeed * Time.deltaTime, Space.World);

  • If you want to steer left/right, just not up/down, compute a desired translation in world space, then clamp-out the y:

    var desiredTravel = transform.forward * translationSpeed * Time.deltaTime; desiredTravel.y = 0f; transform.Translate(desiredTravel, Space.World);

  • Or, route all movement via the Rigidbody by setting its velocity instead of teleporting with Transform changes. This lets the physics engine maintain the constraints you've configured:

    rigidbody.velocity = transform.forward * translationSpeed;

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .