Trouble with rb.Addforce(transform.foreward)

I know this is a noob problem but I’ve been searching the web for a solution for hours and nothing I’ve tried has worked. I’m trying to launch an instance of a projectile on the local z axis as it is instantiated from the cannon’s script.

Projectile Script:

#pragma strict

var rb:Rigidbody;
var ballInitialVelocity:int;

function Start () {
	rb = GetComponent(Rigidbody);
	rb.AddRelativeForce(transform.forward * ballInitialVelocity);
}

And this is the line of code that instantiates it:

Instantiate(redBall, transform.position + 2 * transform.forward, transform.rotation);

It looks pretty good to me, but the instance has no velocity when it instantiates. Can anyone figure out what I’m doing wrong?

This makes no sense:

rb.AddRelativeForce(transform.forward * ballInitialVelocity);

either use

rb.AddForce(transform.forward * ballInitialVelocity);

or

rb.AddRelativeForce(Vector3.forward * ballInitialVelocity);

Both will do exactly the same. Also it doesn’t make much sense to declare ballInitialVelocity as “int”. Change it into a float and make sure you actually assigned a value in your prefab

I am still pretty new to Unity as well, and I came across your post looking to learn a bit more about being able to move rigid bodies using RigidBody.AddForce instead of transform.position (it is messing with my collisions). One thing that might help you is I know when using transform.position I must also use Time.delta in order to get it to move properly. It could be another way for you to get your bullets to move instead of rb.addforce too. Check it out:

example

float MovSpd = 5.0f;

transform.position += transform.forward x Time.deltaTime x MovSpd;

Don’t use “relative” force in this context, tranform.forword is a vector in world, not local space. If you want something to shoot straight out of the weapon using AddRelativeForce, use this parameter, “Vector3.forward * ballInitialVelocity” instead. The function will transform force this into the local space of the rigidbody.

the reason your projectile is not moving is because the force is not a persistent property of the RigidBody, it’s an impulse speed that is applied on that frame only.

In order for the force to be applied on a constant basis, you have to put AddForce in an update loop.

void Update()
{
rb.AddForce(transform.forward * forceamount);
}