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 $$anonymous$$ · Jan 28, 2014 at 09:14 PM · c#2dmovement

2D-Enemy AI problem (2problems)

**I just tried to make a simple AI for a 2d-game. The Ai just should follow the player and deal damage when it collides. The 1st problem is, that the enemy slows down, when he gets negative coordinates (maybe its because -- equals +) but i have no clue how to fix this on an easy way, without making thousands of if-statements.*

 using UnityEngine;
     using System.Collections;
     
     public class EnemyAI : MonoBehaviour {
     
             
             public GameObject player;
             public float movementSpeed = 2f;
             // Use this for initialization
             void Start () {
                 player = GameObject.Find ("Player");
             }
             
             // Update is called once per frame
             void FixedUpdate () {
                 
     
                 
                 if(player.transform.position.x < transform.position.x){
                     rigidbody2D.velocity = new Vector2 ((transform.position.x*movementSpeed)*-1,rigidbody2D.velocity.y);
                     
                 }
                 if(player.transform.position.x > transform.position.x){
                     rigidbody2D.velocity = new Vector2 (transform.position.x*movementSpeed,rigidbody2D.velocity.y);
                 
                 }
                 if(player.transform.position.y < transform.position.y){
                     rigidbody2D.velocity = new Vector2 ((transform.position.x*movementSpeed)*-1,rigidbody2D.velocity.x);
                 
                 }
                 if(player.transform.position.x > transform.position.x){
                     rigidbody2D.velocity = new Vector2 (transform.position.x*movementSpeed,rigidbody2D.velocity.x);
                 
                 }
             
                 
             }
         }
     

The 2nd problem is that i dont know how to access the health variable, that is inside of the PlayerHealthscript, from the enemyAI script.

using UnityEngine; using System.Collections;

public class PlayerHealthScript : MonoBehaviour {

 public int maxHealth = 300;
 public int currentHealth = 100;
 public float healthbarLength;
 

 // Use this for initialization
 void Start () {
     healthbarLength = Screen.width/4;
 }
 
 // Update is called once per frame
 void Update () {
     AdjustCurrentHealth(0);

 
     
 }

 void OnGUI(){
     GUI.Box (new Rect(10,10,healthbarLength,20),currentHealth + "/" + maxHealth);
 }
 public void AdjustCurrentHealth(int adj){
     currentHealth += adj;

     if(currentHealth < 0)
         currentHealth = 0;

     if(currentHealth > maxHealth)
         currentHealth = maxHealth;
     if(maxHealth <1)
         maxHealth =1;

     healthbarLength = (Screen.width / 4) * (currentHealth/(float)maxHealth);
 }




}

I would be happy if someone at least can explain me how to solve at least 1 of the 2 problems. It is appreciated to give me tips how to improve my code to make it more efficient. Maybe the way I set this up is completely wrong.

//Sorry for my bad english

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

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by xt-xylophone · Jan 28, 2014 at 10:17 PM

For the first one, Id recommend using LookAt to lookat the player and then simply make them move in their transform.foward direction(this is their locally foward which should be facing the player.

This is way easier than all that up/down/left/right checking.

For the 2nd problem. In the enemy script use a OnCollisionEnter(look these up!) This will trigger when the object it is attached to collides with something(they both need colliders!) It passes in a collision variable and with that you can check if it hit your player and then you can use a GetComponent().AdjustCurrentHealth([some number]).

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 MikeNewall · Jan 28, 2014 at 11:06 PM 1
Share

Using transform.LookAt you'll need to make sure that the Y position of each of your transforms is the same or you could get rotation in the X axis, meaning your forward vector isn't parallel to the ground anymore and your enemy would rotate forwards or backwards.

You could create a new vector using the targets X and Z position, setting Y to 0:

 Vector3 targetPos = new Vector3(target.transform.position.x, 0, target.transform.position.z);

Then look at that vector, and the enemy's X rotation wouldn't change

avatar image xt-xylophone · Jan 29, 2014 at 12:48 AM 0
Share

Yes! ^^ This is important too! I'd recommend ins$$anonymous$$d of setting Y to 0, set it to the Y of the object thats doing the looking.

avatar image
0

Answer by $$anonymous$$ · Jan 29, 2014 at 05:20 PM

Thanks, your tips kind of worked. The only problem was, that my enemy rotatet 270 degrees on the x axis but i fixed it by adding

 transform.rotation = Quaternion.Euler (lockRot,lockRot,lockRot);

lockRot is a variable set to 0.

It isnt the fine way but it works. I also changed the vector 3 to vector 2 because i dont like to mix up 2d and 3d.

And the enemy now moves that way:

         targetX = target.transform.position.x;
         targetY = target.transform.position.y;
 
         Vector2 targetPos = new Vector2(targetX,targetY );
 
         transform.LookAt(targetPos);
 
         rigidbody2D.velocity= transform.forward*movementSpeed;

Just want to say thank you again ;)

Comment
Add comment · Show 1 · 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 xt-xylophone · Jan 29, 2014 at 07:39 PM 0
Share

Sweet. Also btw for the forums, dont put something like this as an answer, put it as a comment, the little comment button at the bottom.

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

19 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

Related Questions

Making a bubble level (not a game but work tool) 1 Answer

making an object move to a certain point 3 Answers

How to make sprites in SideScroller move in smooth curves 0 Answers

Game object should move like a fish in 2D C# 1 Answer

I need a script in C# which moves an object in only one direction at a time. 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