Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

enemy goes through walls

Discussion in 'Scripting' started by AtomicCabbage33, Oct 11, 2015.

  1. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    my enemy can go through walls. I know I need to add a rigid body to my enemy but when I do that the movement gets messed up and they end up floating around. How do I stop them going through walls without messing up the movement?

    Code (JavaScript):
    1. var Distance;
    2. var Target : Transform;
    3. var ShootRange = 25.0;
    4. var attackRange = 15.0;
    5. var moveSpeed = 5.0;
    6. var Damping = 6.0;
    7. var projectile : Rigidbody;
    8. var fireRate : float = 1;
    9. var FireRange = 0-100;
    10. private var nextFire : float = 0.0;
    11. function Update ()
    12. {
    13.         Distance = Vector3.Distance(Target.position, transform.position);
    14.      
    15.         if (Distance < ShootRange)
    16.         {
    17.                 GetComponent.<Renderer>().material.color = Color.yellow;
    18.                 lookAt();
    19.         }
    20.      
    21.         if (Distance > ShootRange)
    22.         {
    23.                 lookAt();
    24.              
    25.         }
    26.      
    27.         if (Distance < attackRange)
    28.         {
    29.                 GetComponent.<Renderer>().material.color = Color.red;
    30.                 attack ();
    31.         }
    32.      
    33.         if (Distance > attackRange && Time.time > nextFire )
    34.         {
    35.         nextFire = Time.time + fireRate;
    36.                 Instantiate(projectile, transform.position, transform.rotation);
    37.              
    38.         }
    39. }
    40. function lookAt ()
    41. {
    42.         var rotation = Quaternion.LookRotation(Target.position - transform.position);
    43.      
    44.         transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
    45.                      
    46.      
    47.      
    48. }
    49. function attack ()
    50. {
    51.         transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    52. }
     
  2. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    So there are some issues that you need to know. The way you move your enemies is not the best behaviour type for character movement. Best results are usually obtained by using these three:


    If you use Navmesh Agent, your movement & rotation will be handled by that class. It's not too hard, you can have a look at the reference page for example scripts and methods. Good thing about navmesh agents, they are not able to move outside of the navmesh area, which you can set up over the editor by going to Window > Navigation tab. It is pretty easy, and when you generate your movement using Navmesh Agent class, your characters / objects will avoid the obstacles on their way and will move "around" them, thus it will be more realistic.

    If you use character controller, your characters won't be able to walk around the obstacles in their way automatically, but they won't pass through objects either. Rigidbody objects won't be able to affect your character controller managed enemies, but your enemies will be able to affect rigidbodies around them.

    If you use Rigidbody, again, there won't be automatic obstacle avoidance, but your enemies won't be able to pass through objects with colliders - considering that your enemies are not moving too fast, if so, there are some adjustments need to be done - , they will be able to affect and get affected by other rigidbodies.

    Now, the thing you do is, moving the enemies using Translate, is not a suitable behaviour type. Because, the engine will try to force the objects position each frame that the Translate is called, whether there is a collider that needs to block the object or not. So, if you insist on using Translate, one way you can use it in is to write a custom object avoidance script. It will be something that uses raycasts, casting lots of rays starting from the pivot of your enemy and going to some directions like forward, backward, right, left, right front corner, left front corner, right behind corner, left behind corner, and will scan for the colliders around. If a collider is detected, you have to manually alter the movement script, disabling the enemy to go to the position where the collider was detected. Seems like you are a beginner, if so, it's gonna be a really hard work & logic for you, specially when there is already a class that can do these things for you without manually coding it, as I said, Navmesh Agent.

    As a result, I suggest you to use Navmesh Agent class.
     
  3. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    is there anyway in which I can keep the current ai script and just prevent it from going thorugh walls by attaching a rigidbody component to the enemy as I do not have the time to write another ai script and am not too bothered about realism.
     
  4. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    If you are not too bothered about realism, then just let your objects go through walls.
    Only way that you can keep the current script, and try to prevent them from going through colliders, is just adding rigidbodies or proper colliders to your objects. But they will mess up, I guarantee that.
     
  5. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    thats going to be a major issue then. I added a rigid body to the enemy which prevented it from going through walls but the enemies movement needed to be adjusted to suit the rigid body. Any ideas on how to adjust the movement so it works with a rigidbody? I know tjhat this is not the best method but I only need the enemies to chase me around a map and shoot me. Cheers. :)
     
  6. lineupthesky

    lineupthesky

    Joined:
    Jan 31, 2015
    Posts:
    92
    Use Rigidbody's movement functions, like MovePosition or AddForce, instead of Translate.
     
  7. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    I have no 'translates' in my script, just transform.position and transform.rotation so I just need to change those to something, right?
     
  8. MrDude

    MrDude

    Joined:
    Sep 21, 2006
    Posts:
    2,569
    Personally I would say use NavMesh is a far better option. All you do is do a raycast to the player and if unobstructed by another collider just set your enemy's target position to the player's transform position. Done.

    I once had to "audition" for a job interview. My task was to create an enemy character that would follow the main character wherever he goes (unless he looses him) but this was way before NavMesh was included in Unity. The solution I came up with was so simple it's not even funny and allowed my enemy to chase my character around walls and corners and what not.

    My solution was simply this:
    1. I would have my enemy just idling around...turning every now and then (so you could add an angle of view element if you wanted to)
    2. Every 1 second I would cast a ray from my enemy to my hero and see if it is obstructed or not
    3. If it was I would just continue idling
    4. If not, I would place a temporary,empty, game object at the player's position and make the enemy run towards that.

    Done.

    If the hero stays in view the game object will update it's position every second. If the player ran behind a wall during that second, the enemy will still have a "last known position" to run to from where it could continue to the search. If the wall was small enough the enemy would spot the hero and continue running. If the hero ran clean past the length of the wall and out the other side, the enemy will see him again, update the target location and move to there.

    This means the enemy would always follow the player unless the player was out of sight for to long but the enemy would always run in open spaces only since the position was not updated if there were any obstacles in the way. For good measure, though, I added a capsule collider to the enemy and a box collider to the walls.

    Worked perfectly...
     
  9. MrDude

    MrDude

    Joined:
    Sep 21, 2006
    Posts:
    2,569
    Now, with NavMesh it's even easier. Every second just do a raycast to see if you can see the player and then set the target position to the player's position and NavMesh will take care of object avoidance automatically.

    Can't imagine why anyone would want to use anything else... but to each their own.
     
  10. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    I tried out the navmesh and the enemy didn't follow the player and just really slowly walked around aimlessly, and yes I did change the movement speed ;). All I want is an enemy which follows me around and when I'm a certain distance away shoots me. I'm a complete noob when it comes to AI sorry
     
  11. MrDude

    MrDude

    Joined:
    Sep 21, 2006
    Posts:
    2,569
    In that case, save yourself a LOT of headaches and just go onto the Asset Store and find the free Stealth demo. In the Learn section of the main website they explain EVERY part of the demo to you INCLUDING exactly what you want to do both with code samples and video BUT if you are too lazy to copy paste code or watch videos, just extract the controller and animations from the sample, drop that on your own character and voila... Instant patrolling AI complete with the ability to attack you if you want to keep that in...

    Stealth demo... Free... Does what you want... Asset Store... go now! :p
     
  12. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    cheers man, exactly what I was looking for, plus it has videos so I can learn what I am doing and right my own in the future :)
     
  13. AtomicCabbage33

    AtomicCabbage33

    Joined:
    Aug 31, 2015
    Posts:
    141
    shame its In c# and not java :(