- Home /
Question by
FPSworrior · Jan 17, 2014 at 02:21 AM ·
raycastcrosshairgun scriptmodify
Raycast to crosshair. Script change.
So I made a gun shooting script that uses raycast, but I want to make it where the gun shoots at the crosshair at the middle of the screen no matter where the gun is positioned. I have a gun script made already I just need it modified to shoot like I want it to.
#pragma strict
var spawnPoint : Transform ;
var speed : int;
var nextFire = 0.0f;
var fireRate = 0.1f;
var ammo = 150;
var ammoText : GUIText;
var shotSound : AudioSource;
var wood : Transform;
var sand : Transform;
var dirt : Transform;
var water : Transform;
var enemy : Transform;
var range = 100;
// Update is called once per frame
function Update () {
if(Input.GetKey(KeyCode.Mouse0) && Time.time > nextFire)
{
if(ammo > 0)
{
Shot();
audio.Play();
ammo --;
}
}
}
function Shot()
{
nextFire = Time.time + fireRate;
var hit : RaycastHit;
var fwd = spawnPoint.TransformDirection(Vector3.forward);
Debug.DrawRay(spawnPoint.position, hit.point);
if(Physics.Raycast(spawnPoint.position, fwd, hit, range))
{
if(hit.collider.tag == "Dirt")
{
Instantiate(dirt, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));
}
if(hit.collider.tag == "Sand")
{
Instantiate(sand, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));
}
if(hit.collider.tag == "Wood")
{
Instantiate(wood, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));
}
if(hit.collider.tag == "Water")
{
Instantiate(water, hit.point, Quaternion.identity);
}
if(hit.collider.tag == "Enemy")
{
Instantiate(enemy, hit.point, Quaternion.FromToRotation(Vector3.forward, hit.normal));
}
}
}
function OnGUI()
{
ammoText.text = "Ammo: " + ammo.ToString();
}
Comment
Answer by robertbu · Jan 17, 2014 at 02:37 AM
If I was doing it from scratch, I might do it differently, but to change your script, replace line 45 with:
var ray = Camera.main.ViewportPointToRay(Vector3(0.5, 0.5, 0.0));
if (Physics.Raycast(ray, hit, range))
So what do I replace and what do I delete? Do I have to take away my fwd or my hit? And do I not use my spawnpoint variable and replace fwd with ray.
$$anonymous$$y changes was to replace line 45 with these two lines. That is, line 45 would become the second line. You could then delete anything referring to spawnPoint.