In unity, I'm working on functionality for a shooting at the mouse position from the player's weapon in a top-down 2d game. I have a working gun that instantiates a bullet prefab, that moves towards the cursor as desired.

Now I want to add variation to the accuracy of the bullet. Ideally I want to get a random number, for example between -5 and 5, and "add" it to the rotation of the bullets velocity on Start(). I want to use a method like this so that the distance the mouse is from the player won't affect the accuracy of the shot.

Here's the code for the Bullet's Start()

void Start()
    mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
    rigidBody = GetComponent<Rigidbody2D>();
    mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = mousePos - new Vector2(transform.position.x, transform.position.y);
    Vector2 rotation = new Vector2(transform.position.x, transform.position.y) - mousePos;
    rigidBody.velocity = new Vector2(direction.x, direction.y).normalized * force;
    float rot = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0, 0, rot + 90);

Is there someway to edit rigidBody.velocity to rotate the direction its set to move in? Or some way to get a similar affect?

The rotation bit is just to rotate the sprite to be inline with the direction, it doesn't affect the velocity.

  • \$\begingroup\$ Why would rotating a velocity vector be any different from rotating any other vector in the engine? Have you tried simply setting rigidBody.velocity = rotationQuaternion * rigidbody.velocity? \$\endgroup\$
    – DMGregory
    Sep 20 at 1:28
  • \$\begingroup\$ I'm sure there's an obvious easy way to do it, I'm very new at unity. I got this kind of working. I'm trying to use a static rotation to make sure its working right at first. This has some really weird behavior though, its going in different directions based on what quadrant my mouse is in relative to the player entity. Is there extra steps to account for the -/+ of the x and y values of the velocity? var rotationQuaternion = Quaternion.Euler(0, 50, 0); rigidBody.velocity = rotationQuaternion * GetComponent<Rigidbody2D>().velocity; \$\endgroup\$
    – dotexe
    Sep 20 at 1:54

1 Answer 1


I got it working using DMGregory's suggestion.

This line is the ticket, just adjust the "20".

rigidBody.velocity = Quaternion.Euler(0, 0, 20) * rigidBody.velocity;

You must log in to answer this question.

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