- Home /
How to shoot raycast with slight random direction?
I want to shoot a raycast to check where my gun has fired, but with the shotgun I'm going to want to randomize the precise direction of the ray slightly with each shot.
How would I do this?
Currently I use if (Physics.Raycast(shotOrigin.position, shotOrigin.forward, out hit, 1000, layerMask))
to shoot a ray straight out (forward) from the barrel of the gun with each shot, so I need to find a way to vary that "forward" angle up a little bit.
Answer by Casiell · Sep 20, 2018 at 12:54 PM
You might want to use Quaternion.AngleAxis. Create a random float for your angle and multiply shotOrigin.Forward by the value you will get from AngleAxis value
Can you show me how this would look in code with an example, because I'm not sure what you mean (as in how to write it correctly)?
Here's my code as it exists right now:
private void RaycastGun()
{
int numberOfBullets = 1;
if (WeaponSelectionController.weaponNumberRightHand == 2) // The Shotgun
{
numberOfBullets = 15;
}
int layer$$anonymous$$ask = ((1 << 10) | (1 << 11) | (1 << 13));
layer$$anonymous$$ask = ~layer$$anonymous$$ask;
RaycastHit hit;
for (int i = 0; i < numberOfBullets; i++)
{
if (Physics.Raycast(shotOrigin.position, shotOrigin.forward, out hit, 1000, layer$$anonymous$$ask))
{
GameObject theObject = hit.collider.gameObject;
if (hit.collider.gameObject.CompareTag("Enemy"))
{
// Do stuff
}
}
}
}
Something like this:
float randomAngle = new System.Random($$anonymous$$Angle, maxAngle);
Vector3 axis = new Vector3(1, 1, 0);
var rotation = Quaternion.AngleAxis(randomAngle, axis);
if (Physics.Raycast(shotOrigin.position, rotation * shotOrigin.forward, out hit, 1000, layer$$anonymous$$ask))
I'm only not sure if I'm using the correct axis, so if you get weird results you might want to tinker with that first.
Cool.
I'll give it a go and see what happens. . . .
Your answer
Follow this Question
Related Questions
Get angle from Object to nearest point of other Object 0 Answers
how to find direction between two points 2 Answers
How to get offset postition after rotation ? (Spent hours figuring it out) 3 Answers
How to add slight angle/rotation variation to transform.forward? 5 Answers
Raycast across angle? 3 Answers