- Home /
Adding force to a projectile? (SOLVED)
Hi, I am relearning how to Unity.. I left it for about two years, and I now have the motivation once more to get back into it! Happy days. Anyway. It's been a while, as you can see... I have forgotten many things.. One of which I can't seem to find an answer that works.
That is my reason for coming to you today. How do you add force to a projectile, so that it moves towards the (AI Controlled, in my case) player when it's fired from the turret.
Irony is I can remember how to make a complex AI character which decides its movements based on raycasting.. But I can't for the life of me crack the code to make the projectile move towards the player(john)... The Aim Target (at) its positioned when John is is range, and visible. Also positioned by raycasting etc.
This is what I have so far (ORIGINAL CODE).
function Fire()
{
if(canFire)
{
canFire = false;
yield WaitForSeconds(Random.Range(0,2)); // random firing time
var proj : Transform;
proj = Instantiate(pre, spawn.transform.position, transform.rotation);
proj.rigidbody.AddForce((at.transform.position - transform.position) * Time.deltaTime * 500);
// ^ el diablo line
yield WaitForSeconds(5);
canFire = true;
}
}
WORKING CODE: function Fire() { if(canFire) {
canFire = false;
yield WaitForSeconds(Random.Range(0,2));
var proj : Transform;
proj = Instantiate(pre, spawn.transform.position, transform.rotation);
proj.transform.LookAt(at.transform);
proj.rigidbody.AddRelativeForce(Vector3.forward * 500);
yield WaitForSeconds(5);
canFire = true;
}
}
Thanks for you help -f
Are you sure you have a rigidbody attached to your projectile ?
Use Debug.Log(...) to know the value of "at.transform.position - transform.position" (maybe it's (0,0,0) ?)
Answer by Eric5h5 · May 31, 2013 at 01:42 PM
For simplicity I would use Transform.LookAt followed by Rigidbody.AddRelativeForce (Vector3.forward). You should not use Time.deltaTime when adding the force. Also, using integers in Random.Range(0, 2) will pick either 0 or 1, which is unlikely to be what you want.
Hey! I added this code: proj.transform.LookAt(at.transform); proj.rigidbody.AddRelativeForce(Vector3.forward);
after the projectile was instantiated.. But I'm still having the same problem: it just falls to the ground. Any suggestions?
You never told that it falls to the ground :). Do you have the gravity check box ticked in the inspector for your projectile ?
$$anonymous$$y bad. Forgot to mention that... Anyway, yea, gravity is checked.