- Home /
How to make a 2Dgun shoot at the position of mouse?
I've alredy made a gun that rotate's in one place and it's facing mouse and it's eaven shooting but it spawns bullets sideway to camera and it's invisible but colider and rigidbody works. But i want my bullets to be visible please HELP.
This is code:
using UnityEngine;
using System.Collections;
public class RuchyGracza : MonoBehaviour {
private Vector3 mouse_pos;
private Vector3 object_pos;
private float angle;
private float bulletSpeed = 500f;
public GameObject[] ammo;
void Start () {
}
void Update(){
}
void FixedUpdate () {
Vector3 mouse_pos = Input.mousePosition;
Vector3 player_pos = Camera.main.WorldToScreenPoint(this.transform.position);
mouse_pos.x = mouse_pos.x - player_pos.x;
mouse_pos.y = mouse_pos.y - player_pos.y;
float angle = Mathf.Atan2 (mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
this.transform.rotation = Quaternion.Euler (new Vector3(0, 0, angle));
if(Input.GetButtonDown("Fire1")){
if(Input.GetMouseButtonDown(0)){
int ammoIndex = 0;
GameObject bullet = (GameObject)Instantiate(ammo[ammoIndex], transform.position, transform.rotation);
bullet.transform.LookAt(mouse_pos);
bullet.rigidbody2D.AddForce(bullet.transform.forward * bulletSpeed);
}
}
}
}
Answer by robertbu · May 16, 2014 at 01:03 AM
Assuming your bullets are Sprites or Quads, your problems is in the use of LookAt(). Instead you can do:
if(Input.GetButtonDown("Fire1")){
if(Input.GetMouseButtonDown(0)){
int ammoIndex = 0;
GameObject bullet = (GameObject)Instantiate(ammo[ammoIndex], transform.position, transform.rotation);
bullet.rigidbody2D.AddForce(bullet.transform.right * bulletSpeed);
}
}
This assumes your bullet and your shooter is facing right when they have a rotation of (0,0,0).
Answer by Cherno · May 16, 2014 at 12:55 AM
This line:
Vector3 mouse_pos = Input.mousePosition;
is wrong. Check the Unity Script Reference; Input.mousePosition is in pixel coordinated and has nothing to do with the world coordinate system.
To shoot at the point that you aim at with the mouse cursor, you can use a raycast:
Ray mouseRay = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
void Update() {
if(Input.GetMouseButtonDown(0)) {
if(Physics.Raycast(mouseRay, out hit, Mathf.Infinity) == true) {
ShootBullet(hit.point);
return;
}
}
}
void ShootBullet(Vector3 hitPoint) {
GameObject bullet = Instantiate(ammo[ammoIndex], transform.position, transform.rotation) as GameObject;
bullet.transform.LookAt(hitPoint);
bullet.rigidbody2D.AddForce(bullet.transform.forward * bulletSpeed);
}
@Cherno - he does a WorldToScreenPoint and calculates the angle based on the screen coordinates, so his rotation code looks fine.
I stand corrected, thank you. It's an interesting way to do things :)
Answer by RamujTo · May 16, 2014 at 01:36 PM
Thank you very much for all responds now it's working perfect now!
Please post comments as comments, not answers.
Also, please mark the right answer as accepted.