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);
}
}
}
}
Cherno
May 16, 2014, 12:55am
2
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);
}
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).
Thank you very much for all responds now it’s working perfect now!