AddForce problem

Hello Guys . Im working at a 3d game that have a 2d perspective. I have a spear Dispenser and i want to generate arrows and applied them a force on negativ z axis . This is the routine:

private IEnumerator generateArrow(int delay)
{
    alreadyShoot = true;
    GameObject arrow = Instantiate(arrowPrefab);
    arrow.transform.SetParent(parentDispenser);
    arrow.transform.position = arrowStart.position;
    arrow.GetComponent<Rigidbody>().AddForce(-Vector3.forward * shootForce, ForceMode.Impulse);
    yield return new WaitForSeconds(delay);
    alreadyShoot = false;
}`

The arrowPrefab have the (90,0,0) rotation .The arrowStart have (0,0,0) rotation .
The problem is that the force is not applied as desired. I want the arrow go on negativ z .

Note: I editted your question so the code is formatted correctly, use the ‘Code Sample’ button in the future to paste code.

There is limited information here but it seems like the problem could be related to the arrow’s local coordinate system. When you set the arrow as a child of the dispenser, it inherits the dispenser’s coordinate system. Instead of using -Vector3.forward, which applies force in the negative Z-axis of the world coordinate system, you should apply force in the local coordinate system of the arrow or the dispenser.

You can use TransformDirection to convert a direction from the local coordinate system of the dispenser to the world coordinate system. Modify your code like this:.

private IEnumerator generateArrow(int delay)
{
    alreadyShoot = true;
    GameObject arrow = Instantiate(arrowPrefab);
    arrow.transform.SetParent(parentDispenser);
    arrow.transform.position = arrowStart.position;

    Vector3 localForceDirection = -Vector3.forward * shootForce;
    Vector3 worldForceDirection = parentDispenser.TransformDirection(localForceDirection);
    arrow.GetComponent<Rigidbody>().AddForce(worldForceDirection, ForceMode.Impulse);

    yield return new WaitForSeconds(delay);
    alreadyShoot = false;
}

This should ensure that the force is applied correctly in the local negative Z-axis direction of the dispenser, regardless of the dispenser’s rotation in the world space.