- Home /
Raycast only works while moving
I've written a code that checks if the character is looking at a gun on the ground. If he is and presses E while doing so it picks the gun up (changes the gun on ground to inactive and gun in hand to active). The code works but for some reason only detects that it's looking at a gun while the character is moving. Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookingRaycast : MonoBehaviour {
public GameObject GunOnGround;
public GameObject GunInHand;
public Camera camera;
RaycastHit hit;
// Update is called once per frame
void FixedUpdate () {
Ray forwardRay = new Ray(camera.transform.position, transform.forward);
if (Physics.Raycast(forwardRay, out hit))
{
if (hit.collider.tag == "Gun")
{
Debug.Log("Gun Hit");
if (Input.GetKeyDown("e"))
{
GunOnGround.SetActive(false);
GunInHand.SetActive(true);
}
}
}
Debug.DrawRay(camera.transform.position, transform.forward * 1000, Color.green);
}
}
Answer by Santifocus · Sep 21, 2019 at 05:36 PM
My guess would be that you should either use a LayerMask because currently the Raycast will collide with the player which probably doesnt happen when you move, or you use RaycastAll which is a little more expensive and you have to loop througth all hits and check their tags.
if (Input.GetKeyDown(KeyCode.E))
{
Vector3 forward = new Vector3(); //Put your forward dir here
Vector3 origin = new Vector3(); //Put your origin dir here
int gunLayerID = 10; //replace 10 with the collider layer ID of guns
int gunMask = 1 << 10;
RaycastHit gunHit;
if (Physics.Raycast(origin, forward, out gunHit, Mathf.Infinity, gunMask))
{
//Do your stuff here
}
}
Also i would recommend doing less performand requiring stuff such as testing for input as the first IF statement so the raycast which cost more is only done when you actually give the input
Your answer
Follow this Question
Related Questions
Raycasting is hitting objects and not hitting them at the same time 1 Answer
RaycastHit always returns 0 1 Answer
Another Raycast Issue. 0 Answers
Diagonal Movement Question 1 Answer