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.
rigidBody.velocity = rotationQuaternion * rigidbody.velocity
? \$\endgroup\$var rotationQuaternion = Quaternion.Euler(0, 50, 0); rigidBody.velocity = rotationQuaternion * GetComponent<Rigidbody2D>().velocity;
\$\endgroup\$