• 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 decerto · Apr 27, 2012 at 08:38 AM · aienemyshoot

How to make this enemy script shoot upwards?

Hey,

I'm new to unity and I have t$$anonymous$$s script for one of my enemies. The only problem is that I've been trying to make them shoot upwards when I jump in the air. They only seem to shoot straight and not on the Y axis. I've been looking for a solution on the internet for a couple of days now, but without any luck so I decided to try here.

Thank you for your time!

 private var target : Transform; 
     var rotateSpeed = 20;
     var moveSpeed = 5;
     var $$anonymous$$tPoints = 10;
     var bulletDEAD : Transform;
     var explosionDEAD :  Transform;
     private var dead : boolean = false;
     private var currentHitPoints = $$anonymous$$tPoints;
     var liftForce = 50;
     var projectile : Rigidbody;
     var Points1 : GameObject;
     var Points2 : GameObject;
     var ScoreAmount = 10;
     var force = 12.0;
     var damage = 5.0;
     var bulletsPerClip = 60;
     static var clips = 20;
     var reloadTime = 0.5;
     var $$anonymous$$tParticles : ParticleEmitter;
     var muzzleFlash : Renderer;
     public var triggerTime = 0.05f;
     private var bulletsLeft : int = 0;
     private var nextFireTime = 0.0;
     private var m_LastFrameShot = -1;
     var bulletVelocity = 40;
 
 
     function Start () {
     // get the ParticleEmitter component from the object
     $$anonymous$$tParticles = GetComponentInC$$anonymous$$ldren(ParticleEmitter);
     
     // emit particles only when we $$anonymous$$t somet$$anonymous$$ng.
     if ($$anonymous$$tParticles)
         $$anonymous$$tParticles.emit = false;
     bulletsLeft = bulletsPerClip;
     
     // search for the player tagger "player"
     if (target == null && GameObject.FindWithTag("Player"))  
             target = GameObject.FindWithTag("Player").transform;
         currentHitPoints = $$anonymous$$tPoints;
          
     }
     
     // function to destroy the object if it gets out of bounds
     function ColliderBoundDamage (damage : float) {    
     var spawner : SpawnManager = GetComponent(SpawnManager);
 
         if (currentHitPoints <= 0)
             return;
 
         currentHitPoints -= damage;
 
         if (!dead && currentHitPoints <= 0) {
             dead = true;                              // changes the "dead" boolean option to true
             Destroy(gameObject);                 // destroy the gameObject
             spawner.amountEnemies -= 1;      // inform the spawn manager about the object's death
 
         }
     }
 
     // function for getting killed by a bullet
     function ApplyBulletDamage (damage : float) {     
     var spawner : SpawnManager = GetComponent(SpawnManager);
 
         if (currentHitPoints <= 0)
             return;
 
         currentHitPoints -= damage;
 
         if (!dead && currentHitPoints <= 0) {
             dead = true;
             Destroy(gameObject);
             Instantiate(Points1, transform.position, Quaternion.identity);     // spawn a 3d text containing information about points
             Instantiate(bulletDEAD, transform.position, transform.rotation); // spawn a dead replacement of the object 
             spawner.amountEnemies -= 1;      // inform the spawn manager about the object's death
             GUIController.MyScoreCounter += ScoreAmount;  // Add scores!
 
         }
     }
     
     //function for getting killed by an explosion
     function ApplyExplosionDamage (damage : float) {  
         var spawner : SpawnManager = GetComponent(SpawnManager);
 
         if (currentHitPoints <= 0)
             return;
 
         currentHitPoints -= damage;
 
         if (!dead && currentHitPoints <= 0) {
             dead = true;
             Destroy(gameObject);
             Instantiate(Points2, transform.position, Quaternion.identity);     // spawn a 3d text containing information about points
             Instantiate(explosionDEAD, transform.position, transform.rotation); // spawn a dead replacement of the object 
             spawner.amountEnemies -= 1;      // inform the spawn manager about the object's death
             GUIController.MyScoreCounter += ScoreAmount;  // Add scores!
         }
     }
     
 
     function FixedUpdate () {
         if (target == null)
             return;
         
         var direction  = transform.TransformDirection(Vector3.forward);
         var $$anonymous$$t : RaycastHit;
 
 
          // the climb object part
         if (Physics.Raycast(transform.position, direction, $$anonymous$$t, 3)) {  // raycast 3 units ahead of the object
             if ($$anonymous$$t.transform.tag == "Climb" && !dead) {           // if the raycast $$anonymous$$ts an object tagged "Climb"
                 transform.rigidbody.AddForce(Vector3.up *liftForce);    // lift the object up until it overcomes the obstacle
             }
         }
                    
             
         // the rotate part
         if (target && !dead) {
             var rot = Quaternion.LookRotation(target.position - transform.position);
             var rotationX = rot.eulerAngles.y;
             var xQuaternion = Quaternion.AngleAxis(rotationX, Vector3(0, 1l, 0));
         
             transform.localRotation = Quaternion.Slerp(transform.localRotation, xQuaternion, Time.deltaTime * rotateSpeed);
             }
         // the shoot part
         // detect the distance between the player and the enemy
         var dist = Vector3.Distance(target.position, transform.position);     
         if ( dist < Random.Range(20, 30) )    // if in range, shoot!
         Fire();
      
         else 
         // if not, keep walking!
         if ( dist < Random.Range(50, 60)  )
         transform.rigidbody.MovePosition(transform.rigidbody.position + transform.TransformDirection(0, 0, moveSpeed) * Time.deltaTime);
     
     }
     
 function LateUpdate() {
     if (muzzleFlash) {
         if (m_LastFrameShot == Time.frameCount) {
             muzzleFlash.enabled = true;
 
             
         } else {
         // Don't show muccle flash if we're not firing
             muzzleFlash.enabled = false;
             enabled = false;
             
             // Play Gunfire sound
             if (audio)
             audio.Play();
             audio.loop = false;
             
                 
             
         }
     }
 }
 
 //the fire part
 function Fire () {
         var fireRate = Random.Range(0.1, 0.2);  // give a small range of fireRate values to the enemies
         
 
     // Keep firing until we used up the fire time
     w$$anonymous$$le( nextFireTime < Time.time && bulletsLeft != 0) {
         FireOneShot();
         nextFireTime += fireRate;
         }
 }
 
 function FireOneShot () {
     var direction = transform.TransformDirection(Random.Range(-0.05f, 0.05f) * triggerTime, Random.Range(-0.05f, 0.05f) * triggerTime, 1);
     var $$anonymous$$t : RaycastHit;
     var clone : Rigidbody;
     
 audio.Play(); // play the shoot sound
 // instantiate a projectile
 clone = Instantiate(projectile, transform.position, transform.rotation);
 // and make it shoot forward by giving it a velocity
 clone.velocity = transform.TransformDirection (Vector3.forward * bulletVelocity);
 // ignore collision with the roof collider so that the enemy doesnt hurt itself from shooting
 Physics.IgnoreCollision( clone.collider, transform.root.collider );
 
     // raycasts forward
     if (Physics.Raycast (transform.position, direction, $$anonymous$$t)) {
         // Apply a force to the rigidbody we $$anonymous$$t
         if ($$anonymous$$t.rigidbody)
             $$anonymous$$t.rigidbody.AddForceAtPosition(force * direction, $$anonymous$$t.point);
             
         
         // spawn $$anonymous$$t particle effects to the normals we $$anonymous$$t
         if ($$anonymous$$tParticles) {
             $$anonymous$$tParticles.transform.position = $$anonymous$$t.point;
             $$anonymous$$tParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, $$anonymous$$t.normal);
             $$anonymous$$tParticles.Emit();
             
             
            
         }
 
         // Send a damage message to the $$anonymous$$t object            
         $$anonymous$$t.collider.SendMessageUpwards("ApplyPlayerDamage", damage, SendMessageOptions.DontRequireReceiver);
         $$anonymous$$t.collider.SendMessageUpwards("ApplyPropsDamage", damage, SendMessageOptions.DontRequireReceiver);
 
     }
     // get bullets left
     bulletsLeft--;
 
     // Register that we shot t$$anonymous$$s frame,
     // so that the LateUpdate function enabled the muzzleflash renderer for one frame
     m_LastFrameShot = Time.frameCount;
     enabled = true;
     
     // Reload gun in reload Time        
      if (bulletsLeft == 0)
       Reload();
       return;    
 }
   
 // a reload function to make sure the enemy isn't overpowered by giving it a brief reload time every 
 // time it shoots
 function Reload (){ 
 // wait for a specific amount of time
 yield WaitForSeconds(reloadTime); 
    
    clips--;
     bulletsLeft = bulletsPerClip; 
 }
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

Answer by bompi88 · Apr 27, 2012 at 01:24 PM

here is your problem i t$$anonymous$$nk:

 // and make it shoot forward by giving it a velocity
 clone.velocity = transform.TransformDirection (Vector3.forward * bulletVelocity);

you should do somet$$anonymous$$ng like:

 var ShootDir : Vector3;
 
 if (!InJump) {
      ShootDir = Vector3.forward;
 } else {
      // Change 0.3 to what fits you.
      ShootDir = Vector3.forward + Vector3(0,0.3,0);
 }
 
 clone.velocity = transform.TransformDirection (ShootDir * bulletVelocity);

The InJump is a boolean you can change in your jump code. You would also have to update your raycast direction with the same value, i t$$anonymous$$nk. PS.: I`m usually coding in c#.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

enemy shoot AI precision 1 Answer

Make enemy more intelligent 0 Answers

How to reach multiple GameObjects' value , enemy AI 1 Answer

how to make an enemy Ai blow up when you shoot it? 2 Answers

ENEMY HEALTH BAR 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