Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This question was closed May 21, 2018 at 01:09 PM by Jaimieself for the following reason:

Problem is not related to the raycast

avatar image
0
Question by Jaimieself · May 20, 2018 at 05:39 PM · raycastraycasthitmouse positionphysics.raycastscreenpointtoray

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;
 }

}

Comment
Add comment · Show 10
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Captain_Pineapple · May 20, 2018 at 06:37 PM 0
Share

I'd guess that you should post your "knockback" function since ther problem is most probably in there.

avatar image Jaimieself Captain_Pineapple · May 20, 2018 at 09:18 PM 0
Share

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.

avatar image winterfluxstudio · May 20, 2018 at 08:43 PM 0
Share

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.

avatar image Jaimieself winterfluxstudio · May 20, 2018 at 09:19 PM 0
Share

Is that not what i already have on line 47 and 48, or have I written it wrong?

avatar image Jaimieself winterfluxstudio · May 20, 2018 at 09:29 PM 0
Share

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.

avatar image winterfluxstudio Jaimieself · May 20, 2018 at 10:10 PM 0
Share

"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

Show more comments

2 Replies

  • Sort: 
avatar image
0

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");
         
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jaimieself · May 20, 2018 at 08:10 PM 0
Share

Ill give it a try, but all the enemies are on the same layer so i would still have the same problem i think.

avatar image Jaimieself · May 20, 2018 at 08:23 PM 0
Share

Yes as i suspected the raycast still hits all of the enemies because they are all on the same layer

avatar image winterfluxstudio Jaimieself · May 20, 2018 at 08:25 PM 0
Share

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?

avatar image
0

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));
             }

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jaimieself · May 20, 2018 at 08:28 PM 0
Share

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.

avatar image winterfluxstudio Jaimieself · May 20, 2018 at 08:31 PM 0
Share

" 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.

avatar image Jaimieself winterfluxstudio · May 20, 2018 at 08:36 PM 0
Share

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.

Follow this Question

Answers Answers and Comments

122 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to project the mouse cursor into 3D space for LookAt? 1 Answer

Physics.Raycast sometimes does not work? 0 Answers

Raycast to middle screen doesn't work 1 Answer

Raycast hit in OnDrawGizmos but not in Update 1 Answer

raycast screenpointtoray isnt working for some reason 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges