- Home /
Random Raycast inside crosshairs
I am trying to get my raycast(bullets) to shoot inside the spread of the crosshairs. The crosshair is made up for 4 GUI.Box's that spread based on a number of things.
Screenshot of what I'm trying to achieve. I would want the raycast to shoot randomly in the green area which is variable based on the crosshairs spreading.
Spread class:
public class spreading
{
public float sSpread = 20;
public float maxSpread = 40;
public float minSpread = 2;
public float spreadPerSecond = 20;
public float spreadWhileShooting = 50;
public float decreasePerSecond = 25;
public float maxForwardSpread = 25;
public float strafeDecrease = 45;
public float moveForwardSpreadPerSecond = 45;
}
Crosshair drawing:
GUI.Box(new Rect(centerPoint.x - (width / 2), centerPoint.y - (newHeight + spread.sSpread), width, newHeight), GUIContent.none, lineStyle);
GUI.Box(new Rect(centerPoint.x - (width / 2), (centerPoint.y + spread.sSpread), width, newHeight), GUIContent.none, lineStyle);
GUI.Box(new Rect((centerPoint.x + spread.sSpread), (centerPoint.y - (width / 2)), newHeight, width), GUIContent.none, lineStyle);
GUI.Box(new Rect(centerPoint.x - (newHeight + spread.sSpread), (centerPoint.y - (width / 2)), newHeight, width), GUIContent.none, lineStyle);
Example shooting that makes crosshair spread
if (Input.GetKey(KeyCode.Mouse0))
{
spread.sSpread += spread.spreadWhileShooting * Time.deltaTime;
Fire();
}
Answer by robertbu · Mar 03, 2014 at 09:02 PM
I'm not sure how the green area is measured. Let's assume that the diameter of the green circle is equal to spread.sSpread. You can get a random point inside that circle by:
Vector3 pos = centerPoint + Random.insideUnitCircle * spread.sSpread / 2.0f;
I don't know how your firing works. If it is Raycasting, then 'pos' would be the position you use to calculate the ray for casting:
Ray ray = Camera.main.ScreenPointToRay(pos);
Sorry I should have made it clear. The green circle is what I added in using photoshop. That is the area I'm not sure how to calculate.
Actually I implemented your code and it looks about right thanks!
You can adjust the size of the circle by dividing by something other than 2.0 or alternately multiplying by something other than 0.5.
Thanks robert I actually played around with dividing it by something else
Your answer
Follow this Question
Related Questions
shooting problem with raycasting 1 Answer
How should I handle masses of bullets? 1 Answer
Shooting style like enter the dungeon 0 Answers
Best way to shoot physical bullets? 2 Answers
Raycasr in my fps? 1 Answer