It shoots in the game but only to the left, and sometimes comes out 2 at a time, no clue how to fix
var bulletPrefab : Transform;
var cam : Transform;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
Instantiate(bulletPrefab,transform.position,Quaternion.identity);
bulletPrefab.rigidbody.AddForce(transform.forward * 1000);
var bullet : Transform;
bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.rigidbody.velocity = new Vector3(Mathf.Sin(cam.eulerAngles.y * Mathf.PI/180),
-Mathf.Sin(cam.eulerAngles.x * Mathf.PI/180),
Mathf.Cos(cam.eulerAngles.y * Mathf.PI/180)) * 100;
}
}
@Chronos-L it is one script with the bullets shooting and the camera angle, @robertbu it’s in the first person and I’m using the mouse to shoot
You didn’t say how you wanted to target things, so here are two scripts. When you say “using the mouse,” you have to consider that it is a perspective camera. So you have consider at what distance in from your mouse position you want to aim. The second script picks a point projecting in front of the mouse position into the scene. The first script uses a raycast and fires at what the raycast hits. To use the scripts, place them on an empty game object just in front of the gun. Drag the prefab to the goPrefab variable in the inspector. They use the left mouse button to fire.
#pragma strict
var bulletPrefab : GameObject;
var defaultDistance : float = 8.0f;
function Update ()
{
if(Input.GetMouseButtonDown(0))
{
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
var v3Pos : Vector3;
if (Physics.Raycast(ray, hit)) {
v3Pos = hit.point;
Debug.Log("Ray hit");
}
else
v3Pos = ray.GetPoint(defaultDistance);
transform.LookAt(v3Pos);
var go : GameObject = Instantiate(bulletPrefab,transform.position,transform.rotation);
go.rigidbody.AddForce(transform.forward * 1000);
}
}
#pragma strict
var bulletPrefab : GameObject;
function Update ()
{
if(Input.GetMouseButtonDown(0))
{
var v3Pos : Vector3 = Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
transform.LookAt(v3Pos);
var go : GameObject = Instantiate(bulletPrefab,transform.position,transform.rotation);
go.rigidbody.AddForce(transform.forward * 1000);
}
}