Need help Instantiating a projectile and adding a force to it, from player position,towards mouse position
public Transform gun;
public Rigidbody bullet;
void Update()
{
if (Input.GetMouseButtonDown(0))
Fire();
}
void Fire()
{
Vector3 mousePosit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//mousePosit.y = 19;
Rigidbody firedProj;
firedProj = Instantiate(bullet, gun.position, gun.rotation);
firedProj.AddForce(mousePosit.normalized * 5000);
}
This is the code I am using currently.The outcome of this is that the projectiles are shot towards the camera position not the mouse position.I am using an RTS bird view camera which you can move by scrolling to the edges with your mouse. So I don't understand why I don't get the mouse position in world space.
Answer by Matthewj866 · Apr 18, 2017 at 05:32 PM
@dspirelja Hi there, and welcome to Unity answers!
This seems to be a bit of a strange way of achieving what you want - why not just make the gun look at the target by using Transform.LookAt()
then applying force to the new bullet along one axis? Specifically, the axis now pointing at the object?
Documentation: https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Example:
void Fire()
{
Vector3 mousePosit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
gun.LookAt(mousePosit);
Vector3 forceToAdd = new Vector3(0f, 0f, 0f); //change these values to whatever you need to make the bullet move along one specific axis
GameObject firedProj;
firedProj = Instantiate(bullet, gun.position, gun.rotation) as GameObject;
firedProj.GetComponent<Rigidbody>().AddForce(forceToAdd);
}
please note this will only apply the force once, so if you need to apply the force consistently you will need to adjust the code to do that.
Hope this helps!
I need a little bit more help, the gun is supposed to rotate to the mouse position?In my case it always rotates to the same position ignoring the mouse position.Could you also help me rotate the player to the same direction where the projectile is shot?
It will never rotate if you are not constantly calling LookAt()
in Update()
and will only update when Fire()
is called.
You can just adapt what I have mentioned above to get the desired effect for the player.
If you run into additional issues when adding this functionality for the player I recommend opening another question.
If my answer solved your problem, please mark it as the answer.
Your answer
