AddForce has no effect on my cannonball.

Hey folks, first post so if something is wrong please let me know?

I am creating an augmented reality game with two cannons shooting at each other, I have a script attached to the barrel of my cannon to instantiate a cannonball to be fired, when a button on the mobile device is pressed.

My problem is that the cannonball appears and simply falls to the ground under the force of gravity, I can fire(spawn) lots and they react with one another but there is no movement in any direction other than the vertical axis.

My code is as follows

var cannonBallPrefab : Transform;

function Update () 
{
    if(Input.GetKeyDown(KeyCode.Menu))
    {
        var cannonBall =  Instantiate(cannonBallPrefab, 
                                                transform.position,
                                                Quaternion.identity) as GameObject;

        cannonBall.rigidbody.AddForce(Vector3.right * 40000);
    }
} 

I have read other peoples attempts to solve this problem but none seem to work, it is rigidbody, not kinematic, I have tried excessively large and small forces, large and small masses, there are no mesh colliders other than that of the cannonball itself.

I really dont know what to do

any help would be amazing

Thanks in advance

Euan Hislop

The default ForceMode of AddForce is ForceMode.Force

ForceMode.Force is intended to be put on an object over various frames.

GetKeyDown will only run for a single frame.

You should look at changing the ForceMode. In this case an Impulse force might work as intended for a realistic cannon effect.

cannonBall.rigidbody.AddForce(Vector3.right* 40000, ForceMode.Impulse);

Note with you applying such a high force, Vector3.right* 40000, your cannon ball is likely to instantly be shot 1000km away.

I've had luck with my code below. It's got a few extra items in there, but successfully spawns at the cannonballSpawn transform and applies force to the instanced ball, relative to the spawn's position and rotation.

var cannonballSpawn : Transform;
var cannonballPrefab : GameObject;
var cannonForce : int;

function Update() {
    if(Input.GetButtonUp("Fire1")) {
        var projectile = Instantiate(cannonballPrefab,
                                     cannonballSpawn.position,
                                     Quaternion.identity);
        projectile.rigidbody.AddRelativeForce(transform.up* cannonForce);//cannon's axis
    }
}

edit:

on taking a look at our codes, the only real difference I see is straight up Instantiating my prefab as a GameObject as opposed to a transform. Maybe there's something happening there?

If you only want to access the Rigidbody of the instantiated object you could do this.

Define a Rigidbody and set it’s velocity along z-axis:

var cannonBall : Rigidbody =  Instantiate(cannonBallPrefab, transform.position, Quaternion.identity);
cannonBall.velocity = transform.TransformDirection (Vector3.forward * factor);