- Home /
Perspective issue with railgun/raycasting
I would like to create a Railgun in the style of Quake. Here is what i achieve so far :
That's okay but this is because I target the void. When I target an object closer to the player, here the ground for instance, the beam isn't on the crosshair :
An other exemple :
So the raycast and the line renderer are starting from the guntip of my railgun and i think this is a problem of perspective (because the gun isn't align with the camera).
Here is the script i use (I took this script from the survival shooter tutorial project, and tweaked it a little bit):
using UnityEngine;
public class RailgunShot : MonoBehaviour
{
public int damagePerShot = 1;
public float timeBetweenBullets = 1f;
public float range = 100f;
float timer;
Ray shootRay;
RaycastHit shootHit;
LineRenderer gunLine;
float effectsDisplayTime = 0.1f;
void Awake()
{
gunLine = GetComponent<LineRenderer>();
}
void Update()
{
timer += Time.deltaTime;
if (Input.GetButton("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
{
Shoot();
}
if (timer >= effectsDisplayTime)
{
gunLine.enabled = false; //Disable effect.
}
}
void Shoot()
{
timer = 0f;
gunLine.enabled = true;
gunLine.SetPosition(0, transform.position);
shootRay.origin = transform.position;
shootRay.direction = transform.forward;
if (Physics.Raycast(shootRay, out shootHit, range))
{
gunLine.SetPosition(1, shootHit.point);
}
// If the raycast didn't hit anything...
else
{
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
}
}
}
Can you help me solve this ? Thanks in advance.
I believe you are witnessing the unintended side-effect of using the gun's muzzle as the origin for your raycast. Use the camera's position and forward direction as the origin and direction of the ray which deter$$anonymous$$es the hit point. Then extend the beam from the muzzle to the hitpoint.
I believe you are witnessing the unintended side-effect of using the gun's muzzle as the origin for your raycast. Use the camera's position and forward direction as the origin and direction of the ray which deter$$anonymous$$es the hit point. Then extend the beam from the muzzle to the hitpoint.
That's it, this solved my problem, thanks a lot sir.