A Question about Vector3
I have Fps of sorts and I'm trying to instantiate a bullet from a prefab, I know using raycast is a lot more efficient but I'm using a rigidbody anyways. But i seem to cant make the bullet move forward can someone lend a hand?
public class Shooting : MonoBehaviour {
public Transform barrelEnd;
public Rigidbody Bullet;
public float bulletSpeed;
public bool NoAmmo;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation);
Bullet.velocity = transform.TransformDirection(0f, 0f, bulletSpeed);
NoAmmo = true;
}
}
}
Answer by Ahndrakhul · Feb 06, 2016 at 11:11 PM
I don't think you are supposed to alter a rigidbody's velocity directly. Instead, you are supposed to add a force to the rigidbody to make it move. If you really want to alter the velocity, you can do it like this:
using UnityEngine;
public class shoot : MonoBehaviour
{
public GameObject barrelEnd;
public GameObject BulletPrefab;
public float bulletSpeed = 100.0f;
public bool NoAmmo;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject bullet = (GameObject)Instantiate(BulletPrefab, barrelEnd.transform.position, Quaternion.identity);
bullet.GetComponent<Rigidbody>().velocity = (transform.TransformDirection(0f, 0f, bulletSpeed));
NoAmmo = true;
}
}
}
if you want to add force to it, you can just replace the velocity line with:
bullet.GetComponent<Rigidbody>().AddForce(transform.TransformDirection(0f,0f,1f * bulletSpeed), ForceMode.Impulse);
Keep in mind that this will instantiate the bullet inside of the barrelEnd, so if both the barrelEnd and the bullet have colliders, the bullet will collide with the barrelEnd and things won't work right. You can either remove the barrelEnd's collider or instantiate bullets slightly in front of the barrelEnd to fix this problem.
Your answer
Follow this Question
Related Questions
c# help with rotate and rotatearound 0 Answers
iron sight using inverse kinematic 0 Answers
How to disable diagonal Vector3 movement of non-player object using MoveTowards? 1 Answer
how to convert a Vector3 to a float value? 1 Answer
Cannot implicity convert type 'UnityEngine.Vector3' to 'UnityEngine.Quaternion' 1 Answer