Time for action – adding an impulse force to a rigidbody component
Force can be applied to any
GameObject
variable that has a rigidbody
component using Unity's AddForce
function. In the case of our cannonballs, we want to add force to them as soon as they're instantiated; so in this section, we'll be editing our FireCannon
function to include an additional force on any new cannonballs.
To change the properties of an instantiated prefab, we need a variable linked to it. Fortunately, Unity's Instantiate
function returns the instantiated prefab, so we can store that in a new local variable in our FireCannon
function. Perform the following steps to add an impulse:
Modify the call to
Instantiate
in yourFireCannon
function to store the return value in a newGameObject
:void FireCannon() { Vector3 cannonballPos = gameObject.transform.position; cannonballPos.x += 2; cannonballPos.y += 2; GameObject newCannonball = (GameObject)Instantiate(cannonballPrefab, cannonballPos, Quaternion.identity...