- Home /
2d fire from player towards mouse
I am trying to make a bullet fly in the direction the mouse is located in relation to the player character.
What I have so far:
public class BulletMove : MonoBehaviour
{
public Rigidbody2D bullet = null;
private float speed = 5f;
void Update()
{
if (Input.GetButton ("Fire1"))
{
Rigidbody2D shot = Instantiate(bullet,
transform.position,
transform.rotation) as Rigidbody2D;
shot.velocity = new Vector2(-1, 0);
}
}
}
This shot.velocity = new Vector2(-1, 0); makes me able to shoot to the left only as its hardcoded numbers but how do I get the position of the mouse to act as direction to shoot?
Answer by Jeff-Kesselman · Jun 23, 2014 at 09:32 PM
Rather then doing this with the velocity, do it by stetting the rotation of the bullet in your Instantiate.
Quaternion has a function to calculate this for you alreadybuilt in: http://docs.unity3d.com/ScriptReference/Quaternion.FromToRotation.html
So removing velocity and something like this??
Rigidbody2D shot = Instantiate(bullet, transform.position, Quaternion.FromToRotation(transform.position, Input.mousePosition)) as Rigidbody2D;
the bullet gets angle depending on my mouse position yes but it has no velocity so it stands still on the scene.
Your answer
Follow this Question
Related Questions
Fire bullet into the direction my player is facing 2D 2 Answers
gameobject goes in the wrong left and right directions 1 Answer
Bullets direction is not good (network) 0 Answers
2D Shooting right only. Doesn't flip direction with character 1 Answer
c# 2D top down, fire projectale which continuously move in a direction 3 Answers