How to rotate a RaycastHit2D off target by a random value so it sometimes misses?

I have a 2D top-down shooter. I want to fire a raycast when a gameobject fires its weapon but I want to add some inaccuracy. I have a normalized direction vector from the shooter to the target, I just can’t figure out how to rotate it off target by a random value so it sometimes misses.

Vector2 direction = (nearestZombie.transform.position - transform.position).normalized;

RaycastHit2D hit = Physics2D.Raycast(
            transform.position,
            direction,
            weaponRange
            );

I think:

direction = Quaternion.Euler(0, 0, Random.Range(-value, value)) * direction;

Should work?

If not, you’ll need to use a simplified rotation matrix:

x = x * cos(value) - y * sin(value);
y = x * sin(value) + y * cos(value);

(I think that’s right)

2 Likes