ncp12
May 10, 2021, 11:13pm
1
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!!
ncp12
May 11, 2021, 6:29pm
2
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?