• 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 /
avatar image
0
Question by EricsUnityAccount · Nov 09, 2021 at 08:32 PM · raycastraycastingdetection

Raycast not detecting a hit from far away, it only detects when close.

Hello, I am new to gamedev and I am trying to learn, unity, and coding (I am trying c#), t$$anonymous$$s is also my first post so I will describe my issue the best I can. I have been stuck on t$$anonymous$$s problem for a long time now (about 2 weeks). I have a 3d game that I have been working on and ran into an issue where the raycast wont $$anonymous$$t the enemy from far away (I have a debug.log telling me if I $$anonymous$$t the enemy or missed), it only $$anonymous$$ts the enemy when he is really close to the player (about 1 unit maybe). I have spent my time researc$$anonymous$$ng and experimenting and cant find a fix. T$$anonymous$$s problem started when I re-worked the way the ragdoll instantiates when the enemy dies, (t$$anonymous$$s fixed issue with the ragdoll making it work just fine). I have re-worked the way the enemy follows the player to be a rigidbody movement to work with physics, but t$$anonymous$$s didn't fix it. I re-worked the raycast to come from the camera, but t$$anonymous$$s didn't fix it. The enemy does has a capsule collider and also a rigidbody. Note I know EnemyHealth says set collider state to false but if I change it to true it still wont fix it. Any help will super helpful, Thankyou

Here is my code

AIController

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class AIController : MonoBehaviour { public NavMeshAgent enemy; public Transform Player; [SerializeField] private float attackDamage = 1f; [SerializeField] private float attackSpeed = 1f; public float movementSpeed = 1f; private float canAttack; [SerializeField] float stoppingDistance;

 void Start()
 {
     Player = GameObject.FindWithTag("Player").transform;
 }

 void FixedUpdate()
 {
     Vector3 direction = (Player.transform.position - transform.position).normalized;
     GetComponent<Rigidbody>().MovePosition(transform.position + direction * movementSpeed * Time.deltaTime);
 }
 
 void Update()
 {
     enemy.isStopped = false;

     if (enemy.remainingDistance > stoppingDistance)
     {
         GetComponent<Animator>().SetTrigger("Chase");
     }

     if (enemy.remainingDistance <= stoppingDistance)
     {
         GetComponent<Animator>().SetTrigger("Attack");
         StopEnemy();
     }
 }

 private void StopEnemy()
 {
     enemy.isStopped = true;
 }

 private void OnTriggerStay(Collider other)
 {
     if (other.gameObject.tag == "Player")
     {
         if (attackSpeed <= canAttack)
         {
             Debug.Log("Damage");
             other.gameObject.GetComponent<PlayerHealth>().UpdateHealth(-attackDamage);
             canAttack = 0f;
         }
         else
         {
             canAttack += Time.deltaTime;
         }
     }
 }

}

EnemyHealth

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class EnemyHealth : MonoBehaviour { public float enemyHealth = 100f; public GameObject ragdoll;

 void Start()
 {
     setRigidbodyState(true);
     setColliderState(false);
 }

 public void DeductHealth(float deductHealth)
 {
     enemyHealth -= deductHealth;

     if (enemyHealth <= 0) { EnemyDead(); }
 }

 public void EnemyDead()
 {
     Destroy(gameObject, 3f);
     GetComponent<Animator>().enabled = false;
     setRigidbodyState(false);
     setColliderState(true);
 }

 void setRigidbodyState(bool state)
 {
     Rigidbody[] rigidbodies = GetComponentsInC$$anonymous$$ldren<Rigidbody>();

     foreach(Rigidbody rigidbody in rigidbodies)
     {
         rigidbody.isKinematic = state;
     }
     GetComponent<Rigidbody>().isKinematic = !state;
 }

 void setColliderState(bool state)
 {
     Collider[] colliders = GetComponentsInC$$anonymous$$ldren<Collider>();

     foreach (Collider collider in colliders)
     {
         collider.enabled = state;
     }
     GetComponent<Collider>().enabled = !state;
 }

}

AK (for the gun/raycast)

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class AK : MonoBehaviour { Ray ray; RaycastHit $$anonymous$$t;

 //Used to damage enemy
 [SerializeField]
 float damageEnemy = 0;

 [SerializeField]
 int currentAmmo;

 //Rate Of Fire
 [SerializeField]
 float rateOfFire;
 float nextFire = 0;

 [SerializeField]
 float weaponRange;

 void Update()
 {
     if(Input.GetButton("Fire1")&& currentAmmo >0)
     {
         Shoot();
     }
 }

 void Shoot()
 {
     if(Time.time > nextFire)
     {
         nextFire = Time.time + rateOfFire;

         currentAmmo--;

         ray = Camera.main.ScreenPointToRay(transform.position);
         if (Physics.Raycast(ray, out $$anonymous$$t, weaponRange))
         { 
             if($$anonymous$$t.transform.tag == "Enemy") 
             {
                 Debug.Log("Hit Enemy");

                 EnemyHealth enemyHealthScript = $$anonymous$$t.transform.GetComponent<EnemyHealth>();
                 enemyHealthScript.DeductHealth(damageEnemy);
             }
             else 
             {
                 Debug.Log("Missed");
             }
         }
     }
 }

}

Comment
Add comment · Show 2
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 unity_ka6jgzfPPmtNCw · Nov 10, 2021 at 06:49 AM 0
Share
avatar image EricsUnityAccount unity_ka6jgzfPPmtNCw · Nov 10, 2021 at 12:08 PM 0
Share

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

185 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 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

Raycast causes all enemies to attack 1 Answer

Raycast With Innaccuracy Sometimes Going Through Target 0 Answers

How to check if an empty GameObject is inside an object? 2 Answers

How can I make a raycast move towards an object? 1 Answer

ray cast not working ? 2 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