- Home /
This post has been wikified, any user with enough reputation can edit it.
2d shooting.
I want that my shotgun would shot where it points. But now it only shoots left or right. How can i make it shoot where i point. My shotgun follows cursor.
My script:
var Spawn : GameObject;
var speed : float;
var bullet : Rigidbody2D;
var facingR : boolean;
var CanFire : boolean;
var FireRate : float;
function Start () {
facingR = true;
CanFire = true;
}
function Update () {
if(Input.GetKeyDown(KeyCode.A)) {
facingR = false;
}
if(Input.GetKeyDown(KeyCode.D)) {
facingR = true;
}
if(Input.GetButton("Fire1")){
Fire();
}
}
function Fire() {
if(facingR == true && CanFire == true) {
clone = Instantiate(bullet, Spawn.transform.position, Spawn.transform.rotation);
clone.AddForce(Vector2.right * speed);
audio.Play();
CanFire = false;
yield WaitForSeconds (FireRate);
CanFire = true;
}
if(facingR == false && CanFire == true) {
clone = Instantiate(bullet, Spawn.transform.position, Spawn.transform.rotation);
clone.AddForce(Vector2.right * -speed);
audio.Play();
CanFire = false;
yield WaitForSeconds (FireRate);
CanFire = true;
}
}
Comment
Answer by robertbu · Jan 19, 2014 at 05:45 PM
When you say "where i point," I assume you want to shoot in the direction of the mouse.
var myPos = Camera.main.WorldToScreenPoint(transform.position);
var dir = myPos - Input.mousePosition;
clone = Instantiate(bullet, Spawn.transform.position, Spawn.transform.rotation);
clone.AddForce(dir.normalized * speed);
Your answer
![](https://koobas.hobune.stream/wayback/20220613130834im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2d shooting. 0 Answers
slingshot script - velocity help needed 1 Answer
Shooting 2D - how to fix 1 Answer
Is is possible to replace a prefab with a variant in script? 1 Answer