Can't figure out how to move an object along an x any y through an angle and distance

I can’t figure out a problem I have. It goes like this:

Let’s say I have an object (2d for simplicity’s sake) at (0, 0) and i want to move the object at an angle a distance then set an objects x and y to that. I thought it when something like: x/y = distance * sin/cos(angle). But this dose not seem to work for me. I’ve tried swapping sin and cos, but that doesn’t work. All the player dose is spin rapidly with little to no control. How do I fix this problem? Is sin/cos even the right thing to do?

Camera always looks at the player. Here is my script:

public class PlayerMovementScr : MonoBehaviour
{
    PlayerInput input;

    Vector3 move;

    float moveAngle;
    float moveAngleRelative; //Move angle RELATIVE to the camera
 
    public GameObject playerCamera;

    public float moveSpeed = 1.0f;

    void Awake()
    {
        input = new PlayerInput();

        input.Gameplay.Move.performed += ctx => move = ctx.ReadValue<Vector2>();
        input.Gameplay.Move.canceled += ctx => move = Vector2.zero;
    }

    void Update()
    {

        moveAngle = Mathf.Atan2(move.x, move.y) * Mathf.Rad2Deg;
        moveAngleRelative = moveAngle + playerCamera.transform.eulerAngles.y;

        transform.eulerAngles = new Vector3(0, moveAngleRelative, 0);

        Vector3 m = new Vector3(Mathf.Cos(moveAngleRelative), 0, Mathf.Sin(moveAngleRelative)) * moveSpeed * Time.deltaTime;
        transform.Translate(m, Space.World);
    }

    void OnEnable()
    {
        input.Gameplay.Enable();
    }
    void OnDisable()
    {
        input.Gameplay.Disable();
    }
}

I would approach the problem as follows:

  • Convert angle into directional vector
  • Normalize vector (1)
  • Multiply normalized vector (2) by distance to get coordinate
  • Coordinate (3) is the desired position

The only non-trivial part here is converting the angle into a vector. There are a few solutions online.
This should work:
https://answers.unity.com/questions/823090/equivalent-of-degree-to-vector2-in-unity.html?childToView=823224#answer-823224

1 Like

So the thing I was missing was Mathf.Deg2Rad. I just put it in Mathf.Sin(moveAngleRelative * Mathf.Deg2Rad) like so and it’s working as intended. Thank you so much. This was vary helpful

1 Like

Another handy shortcut for producing a vector based on a direction is to multiply a Vector3.forward by the rotation:

float angleDegrees = 123;

var CompassVectorNorth = Quaternion.Eu.er( 0, angleDegrees, 0) * Vector3.forward;
2 Likes

Okay. That will be useful in the future. Thank you so much!

1 Like