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 /
avatar image
0
Question by Ajaxx84 · Sep 09, 2011 at 11:34 PM · collisioncolliderenemydamage

Damage on collision with player..

I have been working on a script for my Enemy AI that I want to lock onto the player, chase it and if it collides with it deals damage to the player. as of right now it is locking on and chasing just fine but when it collides it is not dealing damage. Any idea what I did wrong? (also if any advice can be given as far as to put a timer on how often the collision damage can occur that would be great)

UPDATED SCRIPTS

Enemy Parent

 var HP = 100;
 var runSpeed : float = 5;
 var target : Transform; 
 
 private var controller : CharacterController;
 
 var isChasing : boolean;
 var seeDistance : float = 20;
 
     function Awake(){
     
     controller = transform.GetComponent(CharacterController); 
 
     var playerCount : int = Network.connections.Length +1;
     }     
 
     function Update () {
         
     var tempTarget : Transform = GameObject.Find("Player").transform;
         if (!target){
             if (tempTarget){
             target = tempTarget;
             }
         }
         
     if (target) {     
         var forward : Vector3 = transform.TransformDirection(Vector3.forward);        
         
         transform.LookAt(target);
         transform.rotation.x = 0;
         transform.rotation.z = 0;
         controller.SimpleMove(forward * runSpeed);
         
         var gos : GameObject[];
     gos = GameObject.FindGameObjectsWithTag("Player"); 
     
     var thePlayer:GameObject = gos[0];
     var dist = Vector3.Distance(thePlayer.transform.position,transform.position);
     
     if(dist<seeDistance){
         isChasing= true;
     } else {
         isChasing=false;
     }
         
         }
     }
     
     function ApplyDamage (damage : int) {
         HP -= damage;
         
         if (HP < 1){
             Die();
         }
     }
 
     function Die(){
         Destroy(gameObject);
         gameObject.Find("Player").SendMessage ("Heal", 10);
     }
     
     @script RequireComponent(CharacterController)


Enemy Child

 var damage = 10;
 var hitDelay : float = 0.5;
 private var nextHitAllowed : float;
 
 function OnTriggerEnter (col : Collider) {
     if(col.gameObject.tag == "Player"){
         if(Time.time > nextHitAllowed){
             SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
             nextHitAllowed = Time.time + hitDelay;
     Debug.Log("Hit Player");
         }
     }
 }

Player Script (the one that deals with health and death)

 static var health : float = 100;
 var maxHealth = 100;
 var degen : float = 1;
 
 
 function Update(){
 
         ApplyDamage(degen*Time.deltaTime);
         HealthManager.hitPoints = CharacterDamage.health;
     }
 
 
 function ApplyDamage (amount : float){
 
     health -= amount;
     if(health < 1)
         Die();
 }
 
 function Die(){
     Application.LoadLevel (0);
     }
 
 function Heal(points : float) {
     health = Mathf.Min(100.0, health + points);
     }

Edit Note : Also I noticed that my line CharacterDamage.health += 10; allows for the health value to go over 100 (I assume simply by increasing the number rather then healing? What would I need to do to fix this? I am assuming it is something along the lines of SendMessage("Heal", 10.0, SendMessageOptions.DontRequireReceiver); and adding a heal function to the player?

thanks in advance.

Update : After using Debug.Log I have realized that there is no collision being detected and I have no reason why. Any thoughts on this may solve the issue of not taking damage.

Update 2 : I have solved the healing upon enemy death but can still not get the collission to be detected to apply damage.

Comment
Add comment · Show 1
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 nonaxanon · Feb 18, 2012 at 12:35 AM 0
Share

hi, i know this is an old thread, just wanted a way to communicate with you, and ask 2 things, did you managed to solve your collision problem, and second question is , how would you do to use this script but for a 2d type game, i mean when you use vector3, if the gameobject was facing cam, it will rotate at 90 degrees

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by PrimeDerektive · Sep 10, 2011 at 02:52 AM

OnCollisionEnter() is a rigidbody method, not CharacterController. Even if you add a Rigidbody to your CharacterController object, its wonky at best, they're not really designed to be used together and that's more of a hack.

You could:

-Use OnControllerColliderHit() instead of OnCollisionEnter(). OnControllerColliderHit() is similar to OnCollisionEnter() but for CharacterControllers, except it only fires when this CharacterController is performing a Move command (so if the player runs into the enemy and the enemy isn't moving, OnControllerColliderHit() won't fire on the enemy [but it will fire on the player, because he was obviously moving])

-Make your enemies rigidbodies instead of CharacterControllers (and then use translation/force/velocity instead of move commands)

-Parent a GameObject to the enemy with no renderer and a sphere collider set to be a trigger, and have that send damage messages with OnTriggerEnter().

Edit: Oh, and as for the timer, just make sure that Time.time is greater than the time of the last hit + the delay you want between hits:

var hitDelay : float = 0.5; private var nextHitAllowed : float;

function OnCollisionEnter (col : Collision) { if(col.gameObject.tag == "Player"){ if(Time.time > nextHitAllowed){ SendMessage("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver); nextHitAllowed = Time.time + hitDelay; } } }

Comment
Add comment · Show 8 · 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 Ajaxx84 · Sep 10, 2011 at 03:26 AM 0
Share

Curious you mention that "except it only fires when this CharacterController is perfor$$anonymous$$g a $$anonymous$$ove command (so if the player runs into the enemy and the enemy isn't moving, OnControllerColliderHit() won't fire on the enemy [but it will fire on the player, because he was obviously moving])"

Would this not in a sense create an exploit for the player to where so long as the player stands still they won't take damage? or am I missing something?

so if my enemies are spheres then simply parenting them to an empty game object which has a sphere collider and applying the above script to game object with the aforementioned modifications (OnControllerColiderhit) then removing the script, collider and character controller from the sphere and add a rigidbody should resolve the issue?

avatar image PrimeDerektive · Sep 10, 2011 at 03:33 AM 0
Share

if the Player wasn't moving, then the enemy would HAVE to move for a hit to happen... likewise, if the enemy wasn't moving, the Player would HAVE to move for a hit to happen (in a script on him, not the enemy). So you could conceivably account for both situations by having both the player and the enemies have scripts that call ApplyDamage() on the player in OnControllerColliderHit()). However, if you did that, you'd want to handle the hit delay timer I mentioned in the player's script that contains the ApplyDamage() method, so you couldn't have double hits when both the player and the enemy are moving.

avatar image PrimeDerektive · Sep 10, 2011 at 03:34 AM 0
Share

As for the last part of your comment, you'd probably want to parent an empty gameobject with sphere collider to the enemy, not parent the enemy to it. But then you'd have to add an extra script to that child trigger that handles the damage message sending in OnTriggerEnter(); you wouldn't be able to do that from a script on it's parent.

avatar image Ajaxx84 · Sep 10, 2011 at 04:10 PM 0
Share

Ok I think I am on the right track but am a little bit lost. Sorry I have never created my own enemies before typically I used pre-build models from the asset store so this is a bit of a learning experience for me..

So far I have done the following..

Created an empty game object called Sphere Holder. I have applied a sphere collider set as a trigger, script (handling movement, health, speed, etc) with the adjoining character controller. I have then placed a child component in called Sphere enemy. On that sphere I have the mesh, material, texture, and a rigidbody set to use gravity and be kinematic (if I take kinematic off the child component falls through the terrain upon game start). Now if I am reading this right I am on the right track but on my sphere script I need to remove the damage dealing components and place them in a new script that is applied to the child component? and if I am using OnTriggerEnter do I still need to use OnControllercolliderHit?

Thanks for taking the time to help me.

avatar image PrimeDerektive · Sep 10, 2011 at 04:21 PM 0
Share

The empty gameobject with the sphere collider trigger should be nothing but the collider set to trigger and a single script on it, that send damage messages to the player in OnTriggerEnter(). Then make that gameobject a child of the object with the enemy mesh model, charactercontroller, movement and health script.

Show more comments
avatar image
0

Answer by simonheartscake · Feb 20, 2012 at 03:23 AM

The way I do it is I have a collision detection on the player and if it collides with an enemy then I call a LooseHealth function. as for looking and and moving too I use the LookAt function in mono-develop and and add a forward force.

Comment
Add comment · 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

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

6 People are following this question.

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

Related Questions

How Can One Collider Recognize Contact With Another? 0 Answers

AnimationEvent, Collider, OnTriggerEnter logic? 0 Answers

Decreasing Player Health On Collision with Enemy 2 Answers

My enemy wont take damage 0 Answers

Damage on prefab collision? 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