- Home /
Need help getting bullets to go the right direction is a 2D enviroment
I have this script to shoot bullets towards the mouse cursor but it always shoots it at a 45? degree angle. Heres the script just for the shooting
I have a system to create a bullet and shoot it towards the mouse cursor but I also have an arm that its rotating around.
void pistolShooting() { Vector3 aimPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimPos.z = 0;
//Creating the bullet and shooting it
var pel = Instantiate(Bullet, pistolBulletSpawn.position, pistolBulletSpawn.rotation);
pel.GetComponent<Rigidbody2D>().AddForce(aimPos.normalized * 8000f);
//Playing the bullet noise
//Shot.Play();
//shooting and reloading
usingBulletPerMag -= 1;
}
[1]: /storage/temp/90928-screenshot-82.png
Answer by toddisarockstar · Mar 30, 2017 at 01:34 AM
script is Untested but this is the idea:
Vector3 mp;
RaycastHit hit;
// get mouse position on screen with raycast
// mouse must be on top of object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit)) {
//subtract to get direction
mp = hit.point - pistolBulletSpawn.position;
rigidbody.AddForce (mp.normalized * 8000f);
}
Where would I place the instantiate because if its inside the physics raycast statement, it never spawns.
actually yes, you would put it inside the raycast! and The raycast would need to be inside of a statement that gets the mouse click/button.
this works as long as the mouse click is on top of a collider. if you are unsure put a print statement inside the raycast brackets and another print statement right outside the brackets to locate where the problem is. $$anonymous$$aybe you are not getting the correct rigidbody. or maybe you are not getting the click.
you would need to change my line about the rigidbody to get the correct one. this was just a quick example to show you need a raycast to convert the mouse position to a real location.
heres what I had and im not sure if its wrong or anything
void pistolShooting() {
if (pistolShootable)
{
Vector3 mp;
RaycastHit hit;
// get mouse position on screen with raycast
// mouse must be on top of object
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
var pel = Instantiate(Bullet, pistolBulletSpawn.position, pistolBulletSpawn.rotation);
//subtract to get direction
mp = hit.point - pistolBulletSpawn.position;
pel.GetComponent<Rigidbody2D>().AddForce(mp.normalized * 8000f);
StartCoroutine(pistolFix());
}
}
}
Your answer
Follow this Question
Related Questions
PUN 2, Player A not seeing Player B's hat 0 Answers
Unity 2D - Pivot points based on slice, not on original texture. 0 Answers
Camera Effects for 2d 0 Answers
Unity 4.3, generate 2d mesh 2 Answers
2D C# Jump Script Addforce 2 Answers