- Home /
Raycast LineRenderer, how to set end direction of Ray by transform to the center of the screen or crosshair?
I try to do a simple fps, and I just can't figure how I can do this. I need to change lane 82 of my script to be center of my screen or crosshair, any guidance?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerShooting : MonoBehaviour
{
public int minDmg = 15;
public int maxDmg = 25;
public float timeBetweenBullets = 0.15f;
public float range = 50;
public Texture crossHair;
public Rect middle;
Ray shootRay;
RaycastHit shootHit;
ParticleSystem gunParticles;
LineRenderer gunLine;
AudioSource gunAudio;
Light gunLight;
int shootableMask;
float effectsDisplayTime = 0.2f;
float timer;
void OnGUI()
{
GUI.DrawTexture (middle, crossHair);
}
void Awake ()
{
shootableMask = LayerMask.GetMask ("Shootable");
gunParticles = GetComponent<ParticleSystem> ();
gunLine = GetComponent <LineRenderer> ();
gunAudio = GetComponent<AudioSource> ();
gunLight = GetComponent<Light> ();
}
void Update ()
{
timer += Time.deltaTime;
middle = new Rect((Screen.width - crossHair.width/4) / 2, (Screen.height - crossHair.height/4) /2, crossHair.width /4, crossHair.height/4);
if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
{
Shoot ();
}
if(timer >= timeBetweenBullets * effectsDisplayTime)
{
DisableEffects ();
}
}
public void DisableEffects ()
{
gunLine.enabled = false;
gunLight.enabled = false;
}
void Shoot ()
{
timer = 0f;
gunAudio.Play ();
gunLight.enabled = true;
gunParticles.Stop ();
gunParticles.Play ();
gunLine.enabled = true;
gunLine.SetPosition (0, transform.position);
shootRay.origin = transform.position;
shootRay.direction = transform.forward; //I NEED THIS TO BE THE CENTER OF MY SCREEN OR CENTER OF MY CROSSHAIR
if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
{
EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
if(enemyHealth != null)
{
enemyHealth.TakeDamage (Random.Range(minDmg, maxDmg), shootHit.point);
}
gunLine.SetPosition (1, shootHit.point);
}
else
{
gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
}
}
}
Comment
I'm not asking because I ain't tried this, I'm asking because I tried and i cant figure it out, and need help...
Answer by mesuttasci · Oct 18, 2018 at 02:46 PM
i was looking for a solution to my problem, i found your question. Let me answer, maybe someone will have a problem like yours;)
Line 79 : "gunLine.SetPosition (0, transform.position);" is the starting point of Line. You can change it like gunLine.SetPosition(0, new Vector3(0,0,0));