In my game prototype, I am trying to make the character throw the sword at the end of the animation.
Everything is okay, till the script gets to actually throwing the sword, instead of being thrown smoothly, it teleports to the position in the image below, and gets stuck, not affected by the ground’s collision or even gravity:
Keep in mind, viewing the sword’s rigid body in the inspector while playing, shows that it’s body type is dynamic.
This is the code inside the function that gets called at the end of the throwing animation.
It’s supposed get the mouse direction, separate the sword from the player, enable the Rigidbody2D’s physics, and apply a force in the calculated mouse direction.
//Get mouse direction
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0f;
mouseDir = mouseDir.normalized;
//Get the sword, its rigid body and its collider.
Transform sword = gameObject.transform.Find("WeaponSlot").transform.Find(swordName);
Rigidbody2D swordBody = sword.GetComponent<Rigidbody2D>();
Collider2D swordHitbox = sword.GetComponent<BoxCollider2D>();
//Set parent of the sword to null
sword.parent = null;
//Enable rigid body
swordHitbox.isTrigger = false;
swordBody.bodyType = RigidbodyType2D.Dynamic;
//Apply force
swordBody.AddForce(mouseDir * throwForce);
//Set the states
characterAnimator.SetBool("AimingSword", false);
aimingSword = false;
characterAnimator.SetBool("HoldingSword", false);
holdingSword = false;
Here is the hierarchy of the player’s game object, and its children (RoughSword is the sword I am trying to throw):
The sword’s Rigidbody2D starts off as Kinematic, and it’s BoxCollider2D has “Is Trigger” set to true.
I should say that I just started using Unity, and I apologize if the answer is really basic. I don’t ask on forums, unless I am completely stuck, which in this case I am. Any help is appreciated, thanks!