robertbigcena
robertbigcena

Reputation: 11

Unity: How to limit the rotation of the z axis using Wheel Joint 2D?

I am creating a Jump and run game but you are driving with a car. I use the the Wheel Joint 2D collider and I am also able to jump. Here is my code for the movement:

void Update()
{
    movement = Input.GetAxis("Horizontal");

    if (Input.GetButtonDown("Jump") && IsGrounded())
    {
        carRb.velocity = new Vector2(carRb.velocity.x, jumpForce);
    }

    if (Input.GetButtonUp("Jump") && carRb.velocity.y > 0f)
    {
        carRb.velocity = new Vector2(carRb.velocity.x, carRb.velocity.y * 0.5f);
    }
}

private void FixedUpdate()
{
    backTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    frontTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    carRb.AddTorque(-movement * carTorque * Time.fixedDeltaTime);
}

It works just fine but when I am fast and jump I rotate completely around my own axis and I land on my head and can't move anymore. Therefore I want to limit the rotation of the z-axis to a certain degree so that it won't happen anymore. I looked up how to do it but it doesn't fit for my car-context. Do you have any idea? I would be very grateful

Upvotes: 1

Views: 467

Answers (1)

KYL3R
KYL3R

Reputation: 4073

You have multiple options to solve this:

  • Freeze the rotation axis on the rigibody (very limiting option)
  • Detect the faulty position as "upside-down + grounded" and respawn the vehicle after 2s
  • Forcefully rotate the vehicle back to normal rotation when it's grounded (not in air anymore, so you still allow flips in the air)
  • Limit the angle via script.

Last thing could be done like this:

Vector3 eulerRot = rb.rotation.eulerAngles; // read current rotation
eulerRot.z = Mathf.Clamp(eulerRot .y, minRotation, maxRotation); // clamp it only on z axis.
rb.rotation = Quaternion.Euler(eulerRot); // set clamped rotation

Upvotes: 1

Related Questions