Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 /
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#), this is also my first post so I will describe my issue the best I can. I have been stuck on this 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 hit the enemy from far away (I have a debug.log telling me if I hit the enemy or missed), it only hits the enemy when he is really close to the player (about 1 unit maybe). I have spent my time researching and experimenting and cant find a fix. This problem started when I re-worked the way the ragdoll instantiates when the enemy dies, (this 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 this didn't fix it. I re-worked the raycast to come from the camera, but this 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 = GetComponentsInChildren<Rigidbody>();

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

 void setColliderState(bool state)
 {
     Collider[] colliders = GetComponentsInChildren<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 hit;

 //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 hit, weaponRange))
         { 
             if(hit.transform.tag == "Enemy") 
             {
                 Debug.Log("Hit Enemy");

                 EnemyHealth enemyHealthScript = hit.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

I didn't dig too far into the details, but the most obvious question comes to $$anonymous$$d: Have you tried increasing the weaponRange in the AK class?

avatar image EricsUnityAccount unity_ka6jgzfPPmtNCw · Nov 10, 2021 at 12:08 PM 0
Share

Yes, I had it at 50 and thought the problem might be the range so I increased it to farther ranges but it still didnt work.

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.

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

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

ray cast not working ? 2 Answers

Raycast From Within An Object 1 Answer

Raycast causes all enemies to attack 1 Answer

How to check if an empty GameObject is inside an object? 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