4
\$\begingroup\$

I'm trying to move a 2D object around the mouse position, However, i want to constrain the object from rotating unnaturally around itself, i want it to basically rotate around a radius, similar to how a boat moves. I've provided the boat example below of what i am trying to achieve, the game is called battleboats.io and their rotation around the mouse will not skid, it looks natural like propellers pushing from behind.

This is what i'm looking for

Here's my code for achieving this in unity:

public Camera camera;
public Rigidbody2D rigidbody;

private float rotationSpeed = 200f;
private float acceleration = 4.4f;

Vector3 GetMousePosition(Camera c)
{
    return c.ScreenToWorldPoint(Input.mousePosition);
}

void Update()
{
    Vector3 direction = GetMousePosition(camera) - transform.position;
    direction.Normalize();
    float rotationAngle = Vector3.Cross(direction, transform.up).z;

    //rotation
    rigidbody.angularVelocity = -rotationAngle * rotationSpeed;

    //forward momentum
    rigidbody.velocity = transform.up * acceleration;
}

Any help is appreciated.

What i currently have and the result of my code is illustrated in the below gif. This is what i have

\$\endgroup\$
6
\$\begingroup\$

You need to put a cap on how big rotationAngle is allowed to be. Right now, as the difference between the mouse and the "player" grows larger, your "player" rotates more quickly to catch up. But in order to put a "minimum turn radius" on your object, you need to restrict how quickly it can change direction.

Try this:

float rotationAngle = Vector3.Cross(direction, transform.up).z;

//apply a maximum turn angle of 25 degrees
rotationAngle = Mathf.Max(Mathf.Min(rotationAngle,25), -25);

//rotation
rigidbody.angularVelocity = -rotationAngle * rotationSpeed;

Adjust the "25/-25" as needed to achieve the desired turn rate.

\$\endgroup\$
  • 1
    \$\begingroup\$ That did the trick! I forgot to normalize the direction as well. Thank you :) \$\endgroup\$ – NullOverFlow Jan 9 '18 at 18:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.