x


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;
           }    
    }
}
more ▼

asked Nov 22 '11 at 04:02 PM

MithosAnnar gravatar image

MithosAnnar
299 22 36 40

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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

more ▼

answered Nov 22 '11 at 05:53 PM

monkeyThunk gravatar image

monkeyThunk
66 4 5 7

Thank you! worked perfectly :)

Jan 25 '12 at 03:44 PM MithosAnnar
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x652
x251
x130
x4

asked: Nov 22 '11 at 04:02 PM

Seen: 1189 times

Last Updated: Jan 25 '12 at 03:44 PM