- Home /
 
How do I get my enemy to shoot my player?
Hi,
I am new to unity and c#, I would like to know weather or not it is possible to get a script like this to actually work properly :)
     using UnityEngine;
     using System.Collections;
     
     public class EnemyAI : MonoBehaviour {
     public GameObject objPlayer;
     public GameObject projectile;
     
     
     void Start () {
     
       objPlayer = (GameObject) GameObject.FindWithTag ("Player");
         
     }
         
     
     void Update () {
         if (Input.GetButtonDown("Fire1")) {         
            GameObject clone;
            clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
            clone.transform.TransformDirection(Vector3.forward * 10);
            projectile.transform.position = objPlayer.transform.position;
            }    
     }
 }
 
              Answer by monkeyThunk · Nov 22, 2011 at 05:53 PM
It looks like you are trying to shoot straight forward from you character.
clone.transform.TransformDirection(Vector3.forward * 10)
Multiplying by 10 changes the magnitude / length of the vector, but doesn't change the direction so isn't needed.
 projectile.transform.position = objPlayer.transform.position;
 
               Here, you should be changing your clone's position, not the original projectile (clone.transform.position = objPlayer.transform.position)
You need to make your projectile move!
Check out the documentation for ConstantForce:
// Moves the rigidbody upwards in world coordinates constantForce.force = Vector3.up * 10;
You'll need to add a RigidBody component to you projectile, and may want to uncheck "use gravity"
One tip, Debug.drawRay() and Debug.drawLine() are SUPER useful, I always make sure that I've got the geometric problem solved before trying to make projectiles follow along the paths.
You'll need to make your projectile move along
Your answer
 
             Follow this Question
Related Questions
Rotate object around player when space is pressed. 1 Answer
Unique names for Instantiated prefabs? 1 Answer
Bullets not killing Enemy 1 Answer
find the exact point on which a projectile will hit enemy 3 Answers
How to fire an arrow. C# 2 Answers