- Home /
Raycast Shooting Randomizing
I am trying to make a FPS game where as you fire, the accuracy decreases- you know, where you hold down fire on a Machine Gun and it gets less and less accurate the longer you hold it? Here is part of my fire method (I'm using Raycasts)
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
// Did we hit anything?
if (Physics.Raycast (camera.main.gameObject.transform.position, direction, hit,
range))
{
// Apply a force to the rigidbody we hit
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
Would I have a floating point variable that would increase with every shot, and is added or subtracted from the origin of the Raycast (and it would decrease marginally every half second or so)?
Also, I want to add dynamic crosshairs (the outer bit gets bigger as you fire, representing your hit zone, while the center stays small and...well, centered); I guess that would be done with two different crosshair textures. What would the script (JavaScript) for controlling the crosshair texture that changes size look like?
Example of dynamic crosshairs (sort of)
Thank you for your time!
Answer by aldonaletto · Jan 14, 2012 at 12:09 AM
You could use Random.InsideUnitCircle multiplied by a float variable to add an uncertainty value to the ray:
var uncert: float = 0; var uncertUp: float = 0.2; // uncertainty increased by this amount each shot var uncertDn: float = 0.5; // uncertainty reduced by this amount each second
function Update(){ if (uncert > 0) uncert -= uncertDn Time.deltaTime; // decrease uncertainty over time ... } In the shot routine, add Random.InsideUnitCircle uncert to the forward vector - since Random.InsideUnitCircle is a Vector2, only x and y will be affected:
... private var uncertFwd = Vector3.forward + uncert * Random.InsideUnitCircle; var direction = transform.TransformDirection(uncertFwd); uncert += uncertUp; // increase uncertainty each shot
var hit : RaycastHit; ...
About the crosshair: you could use four GUI.DrawTexture(rect, image) to draw them:
var size: float = 0; // sets the crosshair size var hMark: Texture2D; // drag horizontal mark image here var vMark: Texture2D; // drag vertical mark image here var v = Screen.height/2; var h = Screen.width/2; var vRect = Rect(-2, 0, 4, 9); // set this to the actual vMark width and height var hRect = Rect(0, -2, 9, 4); // set this to the actual hMark width and height
function OnGUI(){ vRect.y = v - vRect.height - size; GUI.DrawTexture(vRect, vMark); vRect.y = v + size; GUI.DrawTexture(vRect, vMark); hRect.x = h - hRect.width - size; GUI.DrawTexture(hRect, hMark); hRect.x = h + size; GUI.DrawTexture(hRect, hMark); }
Thank you for the quick help! However, I cannot get the uncert to decrease at all... I copied the method exactly, and yet when I play, the bullets go all over the place. EDIT: Fixed the problem... I just had to mess with the values of those variables. Thanks!