- Home /
Bullet won't fly forward
Hello, i wrote this script to make my bullet fly:
using UnityEngine;
using System.Collections;
public class HealthShoot : MonoBehaviour {
public GameObject BulletPrefab;
public GameObject cameraobj;
void Start () {
BulletPrefab = Resources.Load("Bullet") as GameObject;
}
void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject projectile = Instantiate(BulletPrefab) as GameObject;
projectile.transform.position = cameraobj.transform.position + cameraobj.transform.forward * 0.6f;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.velocity = cameraobj.transform.forward * 40;
}
}
}
And when i shoot my bullet (depending on what direction i'm turned), bullet fly a little bit to right or left, what's wrong?
Comment
Answer by HarshadK · Jun 29, 2016 at 07:27 AM
Try to set the rotation of the bullet to be same as your camera. You can do something like below:
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject projectile = Instantiate(BulletPrefab) as GameObject;
projectile.transform.position = cameraobj.transform.position + cameraobj.transform.forward * 0.6f;
projectile.transform.rotation = cameraobj.transform.rotation;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.velocity = cameraobj.transform.forward * 40;
}
Your answer
Follow this Question
Related Questions
How can a object be prevented from falling ? 1 Answer
Move object along ray cast using object's AddForce or velocity but not transform 1 Answer
different beetween transform.translat and rigidbody.addforce? 1 Answer
How can I move an object a specific distance using AddForce? 2 Answers
2D character can't jump off of platform floating in water 0 Answers