Easy Directional Force

I wanted to add a directional force and I realized that as long as we only have shooting in the game you can get the direction of the force by getting the selected unit from the UnitActionSystem singleton. Also you can get the type of force later by getting the selected action so you could add an explosion if the selected action is “Grenade” and use a directional force if it’s “Shoot”.

Here’s the simple code:

void ApplyForceToRagdoll(Transform root)
{
Vector3 forceDirection = (transform.position - UnitActionSystem.Instance.GetSelectedUnit().transform.position).normalized;

foreach (Transform child in root)
{
    float randomForceAmount = Random.Range(0,10f);
    if(child.TryGetComponent<Rigidbody>(out Rigidbody rb))
    {
        rb.AddForce(forceDirection * randomForceAmount, ForceMode.Impulse);
    }
    ApplyForceToRagdoll(child);
}

}

I also wanted the ragdoll to drop it’s weapon so I added a rigidbody to the ragdoll’s weapon and a collider and then added a CharacterJoint to it and joined it to the elbow bone. Then after a delay I destroy the bone and unparent the weapon (which is unnecessary but foolproof) Here’s the code:

IEnumerator Start()

{

    // This will make the ragdoll drop it's weapon.

    float delay = Random.Range(0f, 2f);

    Debug.Log(delay);

    yield return new WaitForSeconds(delay);

    _weaponTransform.parent = null;

    Destroy(_weaponTransform.GetComponent<CharacterJoint>());

}
1 Like

This works great for this far in the course! However, once Enemy behaviour is expanded on, the problem will be that there’s no change of the selected Unit during the enemy’s turn. So if a player Unit is killed it will take the last player selected Unit’s position instead of the current enemy Unit’s position.

Yeah! I noticed that too :smiley: It did work before the course continued tho :smiley:

I don’t remember how I solved this later on but it’s still doable.

1 Like

The way I thought to solve it was to make a new Unit reference which can be changed independently of the selected Unit, called activeUnit. During the player’s turn it’s set to the selected Unit, during the enemy’s turn it gets set through the EnemyAI script. It works for both the ShootAction and the SwordAction after that. :smiley:

Passing a damageSource type variable through the HealthSystem script is probably a better solution over all, since things like the GrenadeAction don’t want to base their physics on the Unit which did the action.

1 Like

Privacy & Terms