I am trying to understand the process for creating a 3D projectile in Unity. Of the few online posts about creating a regular, laser-like projectile, there is very little explanation about the process. Can someone please help me understand like a step-by-step methodology of how to approach shooting a projectile.
Problem I am trying to understand:
How to move the projectile in the direction that the shooter GameObject is facing
You use the Camera's Transform.forward
to make the projectile travel towards the position the player is facing.
The Process of shooting a projectile is as below:
1.Instantiate/Create Bullet
2.Set position of the bullet in front of the player
3.Get the Rigidbody
that is attached to that instantiated bullet
4. If this is just Camera with Character Controller and no visible gun,
Shoot the Bullet with Camera.main.Transform.Position.forward
+ shootSpeed
variable.
If there is a visible Gun or Object you want to shoot from,
create another GameObject(ShootingTipPoint) that will be used as the place the bullet should shoot from and position it in the location Gun or Object you want to shoot from, then you use that GameObject's ShootingTipPoint.Transform.Position.forward
to shoot the bullet instead of Camara.Main.Transform.Position.forward
.
And a working code for this:
public GameObject bulletPrefab;
public float shootSpeed = 300;
Transform cameraTransform;
void Start()
{
cameraTransform = Camera.main.transform;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
shootBullet();
}
}
void shootBullet()
{
GameObject tempObj;
//Instantiate/Create Bullet
tempObj = Instantiate(bulletPrefab) as GameObject;
//Set position of the bullet in front of the player
tempObj.transform.position = transform.position + cameraTransform.forward;
//Get the Rigidbody that is attached to that instantiated bullet
Rigidbody projectile = GetComponent<Rigidbody>();
//Shoot the Bullet
projectile.velocity = cameraTransform.forward * shootSpeed;
}