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 ItsLurq · Dec 17, 2014 at 12:14 PM · c#2denemyshoot

Making an enemy shoot at the Players direction (not just up, down, left and right)

Ok, so I'm going pretty well on my game at the moment, but have just come into a slight hiccup but the enemy only being able to shoot in the directions of up, down, left and right, but I would rather the enemy always be able to shoot at the player.

***Ignore the parts of the code that dont really do anything, thats just my testing :)

My code:

 using UnityEngine;
 using System.Collections;
 
 public class AttackingMob : Entity {
 
     public GameObject attackingg;
     
     private bool lookFoward;
     private bool lookBackward;
     private bool lookLeft;
     private bool lookRight;
 
     public Entity attacking;
     public int distance;
     public int minDist = 2;
     //private int maxDist = 5;
     
     private bool canAttack;    
     
     public Rigidbody2D enemyBullet;
     public float enemyAttackRate = 0.25f;
     public float enemyCooldown;
 
     void Start () {
         canAttack = true;
         if(attacking == null){
             attackingg = GameObject.FindGameObjectWithTag ("Player");
             attacking = attackingg.GetComponent<Entity>();
         }
     }
     
     void Update () {
         
         if(Vector3.Distance(transform.position,attackingg.transform.position) <= minDist){
             if(attacking.rigidbody2D.transform.position.y > (rigidbody2D.transform.position.y + distance)) {
                 rigidbody2D.transform.position += Vector3.up * speed * Time.deltaTime;
                 lookFoward = true;
                 lookBackward = false;
                 lookLeft = false;
                 lookRight = false;
             }
             if(attacking.rigidbody2D.transform.position.y < (rigidbody2D.transform.position.y - distance)) {
                 rigidbody2D.transform.position += Vector3.down * speed * Time.deltaTime;
                 lookFoward = false;
                 lookBackward = true;
                 lookLeft = false;
                 lookRight = false;
             }
             if(attacking.rigidbody2D.transform.position.x > (rigidbody2D.transform.position.x + distance)) {
                 rigidbody2D.transform.position += Vector3.right * speed * Time.deltaTime;
                 lookFoward = false;
                 lookBackward = false;
                 lookLeft = false;
                 lookRight = true;
             }
             if(attacking.rigidbody2D.transform.position.x < (rigidbody2D.transform.position.x - distance)) {
                 rigidbody2D.transform.position += Vector3.left * speed * Time.deltaTime;
                 lookFoward = false;
                 lookBackward = false;
                 lookLeft = true;
                 lookRight = false;
             }
         }
         
         if(Vector3.Distance(transform.position,attackingg.transform.position) <= minDist && canAttack){
             if (Time.time >= enemyCooldown){
                 shootAtPlayer();
                 StartCoroutine (waitForAttack ());
             }
         }
     
     //    if(Vector2.Distance (rigidbody2D.transform.position, attacking.transform.position) <= distance && canAttack){
         //    attackEntity();
         //    StartCoroutine (waitForAttack ());
         //}
         if(health <=0){
             Die ();
         }
     }
     
     public void Die(){
         Destroy (gameObject);
     }
     
     public void EnemyDamaged(int amount){
         amount = Staff.realDamage;
         if (health > 0) {
             health -= amount;
         }
         
         if (health <= 0) {
             health = 0    ;    
             Destroy(gameObject);
         }
     }
     
     public void shootAtPlayer(){
         if (lookRight) {
             Rigidbody2D bPrefab = Instantiate (enemyBullet, transform.position, Quaternion.identity) as Rigidbody2D;
             bPrefab.rigidbody2D.AddForce (Vector2.right * 650);
             enemyCooldown = Time.time + enemyAttackRate;
         } 
         if(lookLeft) {
             Rigidbody2D bPrefab = Instantiate (enemyBullet, transform.position, Quaternion.identity) as Rigidbody2D;
             bPrefab.rigidbody2D.AddForce (-Vector2.right * 650);
             enemyCooldown = Time.time + enemyAttackRate;
         }
         if(lookFoward) {
             Rigidbody2D bPrefab = Instantiate (enemyBullet, transform.position, Quaternion.identity) as Rigidbody2D;
             bPrefab.rigidbody2D.AddForce (Vector2.up * 650);
             enemyCooldown = Time.time + enemyAttackRate;
         }
         if(lookBackward) {
             Rigidbody2D bPrefab = Instantiate (enemyBullet, transform.position, Quaternion.identity) as Rigidbody2D;
             bPrefab.rigidbody2D.AddForce (-Vector2.up * 650);
             enemyCooldown = Time.time + enemyAttackRate;
         }
     }
     
     public void attackEntity(){
         int take = Random.Range (1, 20);
         attacking.takeHealth (take);
         //playerBlood.Play();
     }
     
     IEnumerator waitForAttack(){
         canAttack = false;
         yield return new WaitForSeconds(2);
         canAttack = true;
     }
 }

Any help is appreciated!

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

1 Reply

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

Answer by SkaredCreations · Dec 17, 2014 at 12:16 PM

I won't read such long code, so I just point out in the right direction: you will get the direction from the enemy to the player by using (playerTransform.position - enemyTransform.position).normalized

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 ItsLurq · Dec 17, 2014 at 12:23 PM 0
Share

Perfect! Works like a dream! One other question: If I was to make the enemy shoot to where the player will be, any tips on that? Thanks so much!

avatar image SkaredCreations · Dec 17, 2014 at 04:12 PM 0
Share

You're talking about client prediction, that's a totally different question and not trivial but you'll better search Google for calculations and methods about prediction (may be not directly connected to Unity because this is a generic topic). Also think about how frustrating would be for the user if the enemies are so super smart to intercept them while walking/running, I think player's fun is lot more important than AI in games :)

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

my enemy is broken 1 Answer

Multiple Cars not working 1 Answer

C#2d Attacking multiple enemies rather than one 2 Answers

2d c# boss follow code 0 Answers

Enemy bounce from screen edges 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