x


How to make a projectile fly towards it's target

I am trying to implement a turret system which fires arrows at it's target once it collides with the the trigger. here is my code so far

public class ArrowProjectileScript : MonoBehaviour {

public GameObject Target; private Vector3 direction = Vector3.up; public float speed=10.0f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    Target = GameObject.FindWithTag("Enemy");

    GameObject turret = GameObject.Find("Sphere");
    TurretScriptTest ts = turret.GetComponent<TurretScriptTest>();

    if(ts.hit == true)
    {
    direction= transform.Translate(Target.transform);
    transform.Translate(direction*speed*Time.deltaTime);
    transform.LookAt(Target.transform);
    }
}

} Basically in the if(ts.hit == true) statement, I need code which can project the arrow towards the enemy, the transform.LookAt(Target.transform) is already getting the arrow to face the target without much problems. Thanks

more ▼

asked Mar 04 '11 at 03:54 PM

Chris 31 gravatar image

Chris 31
41 15 19 24

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

2 answers: sort voted first

A simple way to correct your code could be(I usually use JS) :

CharacterController ctrl = GetComponent()<CharacterController>;
if(ts.hit == true){
    direction = Target.transform.position-transform.position;
    transform.LookAt(direction);
    ctrl.SimpleMove(transform.TransformDirection(Vector3.forward)*speed*Time.deltaTime);
}

Note that I'm using a CharacterController component. Using transform.Translate doesn't detect collisions and I figure you need your projectiles to be aware of those. Or you could use AddForce, but I'm not a big fan of physics.

Also note that SimpleMove will automatically add gravity, if you don't want that for some reason, take a look at ctrl.Move() instead;

Sorry I didn't test the code, but I figure it should work.

more ▼

answered Mar 04 '11 at 04:06 PM

by0log1c gravatar image

by0log1c
2.1k 6 9 18

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

thanks for the answer, all i had to do was change the direction to Vector3.forward!

more ▼

answered Mar 05 '11 at 12:45 AM

Chris 31 gravatar image

Chris 31
41 15 19 24

(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:

x2176
x1334
x261
x224
x50

asked: Mar 04 '11 at 03:54 PM

Seen: 1556 times

Last Updated: Mar 04 '11 at 03:54 PM