- Home /
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
Answer by by0log1c · Mar 04, 2011 at 04:06 PM
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.
Answer by Chris 31 · Mar 05, 2011 at 12:45 AM
thanks for the answer, all i had to do was change the direction to Vector3.forward!