Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Nazathor · Jan 14, 2014 at 04:00 PM · 2dbeginnertopdownenemy health

Enemy collision in 2D top down

We (my friends and I) are trying to make our player take damage when he collides with the enemies, but needless to say we are having some difficulties. The player stops when colliding with the enemy but the health doesn't go down. Please help?

Note that we are beginners and haven't attempted a project of this size before.

 using UnityEngine;
 using System.Collections;
 
 public class PlayerHealth : MonoBehaviour 
 {
 
     public GUIText healthText;
     public GUIText dieText;
     private int health;
     public float forceSpeed = 0.01f;
     public float speed = 5f;
 
     void Start ()
     {
         health = 12;
         SetHealthText ();
         dieText.text = "";
     }
 
     void FixedUpdate () 
     {
         if(Input.GetKey ("s"))
         {
             transform.Translate(-Vector2.up * speed * Time.deltaTime);
         }
         if (Input.GetKey ("w")) 
         {
             transform.Translate(Vector2.up * speed * Time.deltaTime);
         }
         if (Input.GetKey ("a")) 
         {
             transform.Translate(-Vector2.right * speed * Time.deltaTime);
         }
         if (Input.GetKey ("d")) 
         {
             transform.Translate(Vector2.right * speed * Time.deltaTime);
         }
         
         float moveHorizontal = Input.GetAxis("Horizontal"); 
         float moveVertical = Input.GetAxis("Vertical"); 
         
         Vector3 movement = new Vector3(moveHorizontal, moveVertical);
         
         rigidbody2D.AddForce(movement * forceSpeed);
     }
 
     void OnCollosionEnter(Collider other)
     {
         if(other.gameObject.tag == "Enemy")
         {
             other.gameObject.SetActive(false);
             health = health -1;
             SetHealthText ();
         }
     }
 
     void SetHealthText ()
     {
         healthText.text = "health" + health.ToString();
         if(health == 0)
         {        
             dieText.text = "YOU DIE!";
         }
         
     }
 
 }
Comment
Add comment · Show 3
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 woodoo · Jan 14, 2014 at 04:36 PM 0
Share

Not answering your question, but, i'll give some tips to boost your code and get more performance..

Put all the Input.Get$$anonymous$$ey(..) code inside a function, and after you set the translate according to what key was pressed, you just return, doing it, you won't check the other keys in that Update.

Something like:

 void FixedUpdate()
 {
     Translate$$anonymous$$e();

     /* your code.. */
 }
 
 private void Translate$$anonymous$$e()
 {
     float t = speed * Time.deltaTime;
 
     if (Input.Get$$anonymous$$ey("w"))
         transform.Translate(Vector2.up * t); return;
     if (Input.Get$$anonymous$$ey("s"))
         transform.Translate(-Vector2.up * t); return;
     if (Input.Get$$anonymous$$ey("d"))
         transform.Translate(Vector2.right * t); return;
     if (Input.Get$$anonymous$$ey("a"))
         transform.Translate(-Vector2.right * t); return;
 }
avatar image robertbu · Jan 14, 2014 at 05:46 PM 0
Share

@woodoo - Transform.Translate() is a void, so you cannot return it. You could return the vector used in the Translate() and then Translate() in the caller.

avatar image woodoo · Jan 14, 2014 at 06:03 PM 0
Share

@robertbu - I was just trying to not use another line of code, i would need to open and close a block.. I thought that you could return void in a void function, considering that it returns void :)

The return in this case was just a shortcut to leave the function after translating, cuz there's no need to check other inputs in the current Update..

But if it is not possible to return void, I'll edit the previous comment.

2 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by robertbu · Jan 14, 2014 at 04:04 PM

I spot one problem. You are using the 3D version to detect collisions. For 2D, use OnCollisionEnter2D():

 void OnCollosionEnter2D(Collision2D coll)
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
avatar image
0

Answer by Pangamini · Jan 14, 2014 at 06:23 PM

The answer by robertbu is correct. However, there might be more problems at the same time:

I haven't tried Box2D implementation in Unity yet, but what i can say now is that you are using transform.translate for a rigid body, which in some physics engines, if you translate the body manually, it won't produce correct collisions. To correctly move a rigidbody you should use forces, and velocity for kinematic bodies (that's said in Box2D docs, thouugh using velocity in non-kinematic bodies should work too)

Also, you didn't mention having a rigidbody or a collider (2D versions) on your GameObject, so make sure both are there... OnCollosionEnter2D is a callback of physics engine

Comment
Add comment · Show 2 · 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 Nazathor · Jan 15, 2014 at 12:06 PM 0
Share

Thank you all for answering so quickly!

We have a Rigidbody2D component on the player, and a 2D Box Collider (we are currently just testing with cubes to get the code working). On the "enemy" we also have a 2D Box Collider.

We tried the OnCollisionEnter2D, but the player still went through the object without triggering it.

Update

We transferred the code onto a new scene where we only used sprites, and this time it worked. So we are guessing there must have been a problem with the default 2D boxes.

avatar image Sisso · Jan 15, 2014 at 12:08 PM 0
Share

@Nazathor, I convert your "answer" into a comment.

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

21 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

Related Questions

Multiple Cars not working 1 Answer

How do I get character to always face mouse? 2 Answers

2d ragdoll, where to start? 1 Answer

Introducing joystick to Unity? 0 Answers

Moving the camera with mouse not working 1 Answer


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