- Home /
Offset raycast by specific amount
I have been really struggling with trying to get random deviation to work for hitscan shotguns in my FPS game. The script at the bottom of this more or less just creates a raycast from the camera's center, and shoots 15 raycasts towards the same place.
Obviously, for shotguns, every pellet going to the same place doesn't work. I would like to know if there is a way to properly cause the raycasts to deviate from the center by a set amount, while accounting for the rotation of the player.
I have tried countless things, some of them resulting in (mostly) working functions, though often times, this happens:
As seen here, the spread on the far right is fine and dandy, but when the player turns leftwards, the spread seems to compress into a less vertical shape. I have no idea why that is and I have tried plenty of things to deal with that.
Also to note, while I'm sure I can make it work if you don't account for this, the shotgun is intended to have FIXED spread, so the deviation is not random, but, either way, I still can't get the raycasts to rotate directions without compressing when turning left or right. Facing the same wall diagonally also seems to fix the spread so that it is more like the spread shown on the far right, but I do not understand why the spread is compressing at all?
void fireHuntingShotgun()
{
RaycastHit hShotgunHit = new RaycastHit();
Ray huntingRay = mainCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
for (int i = 0; i < 15; i++)
{
Vector3 spreadAngle = mainCam.transform.forward;
//how to make spreadAngle rotate the raycast without that compression effect?
if (Physics.Raycast(huntingRay, out hShotgunHit, 100f))
{
print(hShotgunHit.distance);
}
}
}
Answer by qobion · Apr 18, 2019 at 12:06 AM
float r = 0.1f;
huntingRay = mainCam.viewportPointToRay(new Vector2(( 0.5f + r * Mathf.Cos(24*i), 0.5f* r * Mathf.Sin (24*i));
Can you explain where I'd put this?
The i is for iterating between an array of different Vector3 values so that I can fix the weapon's spread.
Edit: Also, wouldn't this not be an angle, but just a different origin? That's not what I'm looking for, I'm looking for the starting position to be the same, except the huntingShotgunAngles[i] to be added to the rotation.
Eg, the 0th element of that array is 0f 0f, 0f, so the 0th element is always 100% on point with where the use clicked, but the next is 3f, 4.5f, so I want the ray's location to end up being three degrees upwards and 4.5 to the right.
Your answer
Follow this Question
Related Questions
Rotate a vector WITH transform. 1 Answer
Instantiate Bullet Hole position and rotation, Vector3 issues 1 Answer
Rotation+BoxCast works with Update in game editor, but not when built or in FixedUpdate. 1 Answer
How to get Raycast surface normal to align particle system? 1 Answer
Detect if on ground? 1 Answer