Foreword: I believe everyone is familiar with shooting games. So to achieve this function, we usually use two methods:
1. Ray Tracing.
2. Bullet instantiation.
Today, we use the second method to realize the launch function.
1. First, we prepare a gun model, put it in the scene, and adjust the position.
2. We create an empty object at a point in front of the muzzle, as the launch port, and adjust the position (note: the position of the launcher should not be too close to the gun body)
3. Make a simple bullet. Here we use the capsule body, just change the size and rotation scheduling. (Note: The parameters here are for reference only, and you can add a shader to make it change color)
4. Instantiate and generate bullets. Now, we make the bullets we made into prefabs and create a new script on the gun launcher. (Note: The Rotation of the launcher should be consistent with that of the bullet)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunShoot : MonoBehaviour {
public GameObject bulletPrefab; //子弹预制体
void Update () {
Shoot();
}
void Shoot()
{
if (Input.GetMouseButtonDown(0)) //如果按下鼠标左键,生成预制体
{
Instantiate(bulletPrefab, transform.position, transform.rotation); //生成预制体
}
}
}
Don't forget to drag the prefab of the bullet into the script after writing. Now, we can generate a bullet by pressing the left mouse button, but we can't fire it yet.
5. Let's create a new script for the bullet to make it move.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour {
public float speed = 8f; //子弹速度
void Start () {
Destroy(gameObject, 7f); //7s后销毁自身
}
void Update () {
transform.Translate(0, Time.deltaTime * speed, 0); //子弹位移
}
}
In this way, we can fire a bullet by clicking the left mouse button.