RigidBody add force question

Hi,
I’m currently trying to create a projectile system. I want to launch my projectile from the player to the mouse direction at a constant speed.

I did something like this;

gO.GetComponent<Rigidbody>().AddForce(e.valeur * (Splat.Get3DMousePosition() - this.transform.position));

The direction is working, but if my pointer (mouse) is near the player, it will launch the projectile slowly. And if the mouse is far from the player, the projectile is super fast.

Is there a way to get the direction without having this problem?

Thanks ! And sorry for my bad english !

You could try creating a Vector3 with the direction and normalizing it and then multiplying that with the speed you wanted, I havent tested this code but something like this should work:

Vector3 shotDir;
float shotSpeed=100f; //Change this with whatever value you want

shotDir = new Vector3(mousepos.x - player.x, mousepos.y - player.y, mousepos.z - player.z).normalized;
gO.GetComponent().AddForce(shotDir * shotSpeed);

Obviously this is just pseudo code so you’d have to change all that mousepos.x and player.x for the actual Vector3 containing the mouse and player position but I think that should work, also if the bullet are coming backwards maybe you’d want to try doing player - mouse instead of mouse - player when calculating the direction

Let me know if it helped you
Good luck! :slight_smile:

2 Likes

Ok it worked :

Here’s my code for people having the same problem:

gO.GetComponent<Rigidbody>().AddForce(e.value * (Splat.Get3DMousePosition() - this.transform.position).normalized);

Where e.value is your speed :slight_smile:

Thanks a lot for your time giantSwing I had never seen “normalized” !