Unity3D: Adding force based on direction an object is facing

2.2k views Asked by At

I am trying to make a "worms"-like game where the player can choose the position of an object (the player can move the object around 180 degrees) , and then the force would be added to the direction the object is facing. I tried using transform.right and transform.forward, but the force was not driven towards where the object is pointing. I have looked around A LOT, and still not found/understand what I can do. Heres the code I use for shooting the object:

    void shootIt(){
       transform.parent = null;
        isPlaying = true;
        A.isKinematic = false;
        A.AddForce(transform.up*varSpeed*_multiplier);
} //"A" stands for the RigidBody2D component I got by using GetComponent<Rigidbody2D>();

Help is as always greatly appreciated.

1

There are 1 answers

1
BjarkeCK On BEST ANSWER

Try this:

void shootIt()
{
    Vector2 direction = transform.localPosition.normalized;
    transform.parent = null;
    isPlaying = true;
    A.isKinematic = false;
    A.AddForce(direction*varSpeed*_multiplier);
} 

Also consider forcing yourself to write good names for your variables. A is not very descriptive.