- Home /
Problem is not related to the raycast
Raycast hits everything on the screen
I want to be able to click on one of the enemies on the screen to Start a Coroutine, but when i test the raycast it hits everything on the screen instead of just hitting the thing i click on which is obviously a problem.
I can get it to tell me in the console that it is hitting the object tagged as "Enemy" but if there are more that one enemies on the screen it hits all of them rather than the one I am clicking on
Here is the script that goes on the enemy prefab:
using UnityEngine; using System.Collections;
public class NPC : MonoBehaviour {
public GameObject HealthPack;
private int moveSpeed = 1;
private MovementSpeedManager moveSpeedA;
public int Health = 1;
public Rigidbody coin;
private bool coinHasSpawned = false;
public float coinForce = 1f;
private PlayerGold goldGain;
private PlayerGold totalGold;
public int totalGoldNew;
private int spawnHealthPackNumber;
public Damsell rageMode;
private void Awake()
{
goldGain = GameObject.Find("GoldManager").GetComponent<PlayerGold>();
totalGold = GameObject.Find("GoldManager").GetComponent<PlayerGold>();
moveSpeedA = GameObject.Find("MovementSpeedManager").GetComponent<MovementSpeedManager>();
}
private void Start()
{
totalGold.totalGold = PlayerPrefs.GetInt("TotalGoldNew");
moveSpeed = moveSpeedA.moveSpeedA;
}
void Update ()
{
transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
if (Health <= 0 && coinHasSpawned == false)
{
moveSpeed = 0;
Destroy(GetComponent<Collider>());
Destroy(this.gameObject, 1f);
spawnCoin();
coinHasSpawned = true;
spawnHealthPack();
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100))
{
if (hit.collider.tag == "Enemy")
{
Debug.Log(hit.collider.tag);
StartCoroutine(knockback());
}
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
other.GetComponent<PlayerHealth>().playerHealth --;
}
}
private void spawnCoin()
{
Rigidbody coinInstance = Instantiate (coin, transform.position, transform.rotation) as Rigidbody;
coinInstance.AddRelativeForce(new Vector3(0f, coinForce, 0f), ForceMode.Impulse);
goldGain.goldGain++;
totalGold.totalGold++;
totalGoldNew = totalGold.totalGold;
PlayerPrefs.SetInt("TotalGoldNew", totalGoldNew);
}
private void spawnHealthPack()
{
spawnHealthPackNumber = Random.Range(1, 101);
if(spawnHealthPackNumber >= 99)
{
Instantiate(HealthPack, transform.position, transform.rotation);
}
}
IEnumerator knockback()
{
moveSpeed = moveSpeed * -3;
yield return new WaitForSeconds(0.2f);
moveSpeed = moveSpeedA.moveSpeedA;
}
}
I'd guess that you should post your "knockback" function since ther problem is most probably in there.
Its there at the bottom, line 91, it is actually working fine but it is affecting all the enemies ins$$anonymous$$d of the one that is clicked.
https://docs.unity3d.com/ScriptReference/Camera.ScreenPointToRay.html https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
As far as I can tell, you are neither giving the Ray a "direction" or giving it an "end point". But you are still creating a ray in worldspace... which might be why everything is getting hit. because, without an endpoint or a direction... i assume it doesnt know "where to go or what direction" and just hits everything.
Is that not what i already have on line 47 and 48, or have I written it wrong?
I have added Debug.DrawRay(ray.origin, ray.direction * 10, Color.green); It draws a line from the camera to the position I click, so i know that it is working. I think now that it is because the script is attached to the enemy prefabs so it is running the script on all of the enemies when any one of them is hit.
"Is that not what i already have on line 47 and 48, or have I written it wrong?"
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 10))
print("There is something in front of the object!");
}
docs mention it a few times but not 100% sure if that's your issue. If you have 1 script that all enemies use, and it "does something" when the GameObject it's attached to is hit by the raycast.. then that could be an issue. Could you test by having two gameobjects in your scene, each with a unique script Script1.cs Script1A.cs
Answer by raybarrera · May 20, 2018 at 07:14 PM
Sounds like what you're looking for is a LayerMask: https://docs.unity3d.com/ScriptReference/LayerMask.html
From the docs:
public class ExampleClass : MonoBehaviour {
public LayerMask mask = -1;
void Update() {
if (Physics.Raycast(transform.position, transform.forward, 100, mask.value))
Debug.Log("Hit something");
}
}
Ill give it a try, but all the enemies are on the same layer so i would still have the same problem i think.
Yes as i suspected the raycast still hits all of the enemies because they are all on the same layer
I think the issue might be you are not raycasting properly. Enemies on the same layer should not be an issue. Are you rendering the LineRenderer to visually debug?
Answer by winterfluxstudio · May 20, 2018 at 08:19 PM
Can you post full code? I have no idea if you've accounted for "what happens if the raycast doesnt hit anything... is there a max range etc)
if (Physics.Raycast (rayOrigin, Cam.transform.forward, out hit, maxRange))
{
// hit something
laserLine.SetPosition (1, hit.point);
}
else
{
// hit nothing and reached max range
laserLine.SetPosition (1, rayOrigin + (Cam.transform.forward * maxRange));
}
Sure. Its an isometric view game so range isn't a problem. The only thing the raycast can hit is the ground or the enemy. I can get the code to tell me if its hitting the ground or an enemy but it hits all the enemies ins$$anonymous$$d of one. Ill edit my original post to include the full script.
" Its an isometric view game " hmm, I mostly work in perspective so I don't really know if you're dealing with issues due to it being isometric, or another reason. but yeah, post your full code and it will help people to figure out what is going wrong. Well, the full code for the raycasting so we can see whats going on.
Iv just put the full code up there. Is it possible that the code is affecting all the enemies because they are prefabs and all have the same code attached? I have a feeling that might be the problem.