- Home /
Raycasting
I'm making an fps and I just decided to start with a sniper. Of course, it being a sniper, I used raycasts for the bullets. However, when the sniper is not zooming in, it doesn't have a very accurate raycast.
Here's the code:
variables: public float range = 100f public int bulletsPerMag = 3 public float fireRate = 2f public int currentBullets = 3 float fireTimer public Transform shotPoint
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
void Start(){
currentBullets = bulletsPerMag;
}
void Update()
{
if (Input.GetButton("Fire1")){
Fire();
}
if (fireTimer < fireRate){
fireTimer += Time.deltaTime;
}
}
private void Fire()
{
if(fireTimer < fireRate) return;
RaycastHit hit;
if(Physics.Raycast(shotPoint.position, shotPoint.transform.forward, out hit, range)){
Debug.Log(hit.transform.name + " got pewed");
}
currentBullets--;
fireTimer = 0.0f; //reset fireTimer
}
For example, when I aim like this:
it tells me that I am hitting the floor.
Please help me! Thanks in advance!!
So. Currently you are firing a ray from where the bullet leaves the gun? It seems like the problem is that in that position shotPoint.transform.forward is down. Instead of doing it simply from the object. Try something like this:
https://answers.unity.com/questions/590671/direct-a-raycast-from-point-a-to-point-b.html https://gamedev.stackexchange.com/questions/169933/raycasting-from-an-object-to-the-center-of-the-screen-crosshair-without-clippi
Where you end up raycasting to the crosshair point.
Answer by ncp12 · May 11, 2021 at 06:29 PM
It now detects the red capsules, but doesn't detect the floor.
using System.Collections; using System.Collections.Generic; using UnityEngine;
void Start(){
currentBullets = bulletsPerMag;
}
void Update()
{
if (Input.GetButton("Fire1")){
Fire();
}
if (fireTimer < fireRate){
fireTimer += Time.deltaTime;
}
}
private void Fire()
{
// if(fireTimer < fireRate) return;
// RaycastHit hit;
// if(Physics.Raycast(shotPoint.position, shotPoint.transform.forward, out hit, range)){
// Debug.Log(hit.transform.name + " got pewed");
// }
// currentBullets--;
fireTimer = 0.0f; //reset fireTimer
Vector3 GetHitPoint(Vector3 muzzlePosition) {
Ray crosshair = new Ray(camera.position, camera.forward);
Vector3 aimPoint;
RaycastHit hit;
if(Physics.Raycast(crosshair, out hit, range)) {
aimPoint = hit.point;
} else {
aimPoint = crosshair.origin + crosshair.direction * range;
}
Ray beam = new Ray(muzzlePosition, aimPoint - muzzlePosition);
if(!Physics.Raycast(beam, out hit, range ))
return aimPoint;
Debug.Log(aimPoint);
Debug.Log(hit.transform.name + " got pewed");
return hit.point;
}
GetHitPoint(muzzlePosition);
}
}
I know I wont be hitting the floor, but in case there is an error in the code, or something..Anyone know what's happening?
Your answer
![](https://koobas.hobune.stream/wayback/20220613033555im_/https://answers.unity.com/themes/thub/images/avi.jpg)