This is the 21st day of my participation in the August Text Challenge.More challenges in August
Today to write a unity small tutorial, just to write a small first person shooter game as a case.
First, the effect picture:
First of all, there’s not much in the game: the floor, the parallel light, the main camera. And then we need to make a bullet, and we need to add rigidbodies to the bullet. Then save it as the default body.
Generate the fire.cs file.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fire : MonoBehaviour
{
public int speed =5;
public GameObject newObject;
// Start is called before the first frame update
void Start(){}// Update is called once per frame
void Update()
{
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;
float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
transform.Translate(x, 0, z);
if(Input.GetButtonDown("Fire1"))
{
GameObject n = Instantiate(newObject,transform.position,transform.rotation);
Vector3 fwd;
fwd = transform.TransformDirection(Vector3.forward);
n.GetComponent<Rigidbody>().AddForce(fwd*6000);
Destroy(n, 5);
}
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0.- 50 * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(0.50 * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.Z))
{
transform.Rotate(- 50 * Time.deltaTime, 0.0);
}
if (Input.GetKey(KeyCode.C))
{
transform.Rotate(50 * Time.deltaTime, 0.0); }}}Copy the code
The code hangs directly on the camera. The newObject is just the preset body bullet you just saved.
Code parsing:
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;
float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
Copy the code
Here’s the tube camera, which is moving up and down and left and right in the first person.
if(Input.GetButtonDown("Fire1"))
{
GameObject n = Instantiate(newObject,transform.position,transform.rotation);
Vector3 fwd;
fwd = transform.TransformDirection(Vector3.forward);
n.GetComponent<Rigidbody>().AddForce(fwd*6000);
Destroy(n, 5);
}
Copy the code
Here is the fire button, which is the left mouse button. Take a close look at the code here. This is the default volume generation, which means that if you want to dynamically generate objects with code, you have to learn this part of the code. And the resulting bullet adds a forward force, allowing it to fly out.
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0.- 50 * Time.deltaTime, 0);
}
Copy the code
The rest of the code is the tube keyboard event. Keyboard key input, and then control camera rotation, to achieve the lens left and right up and down rotation effect.
This is a relatively basic simple game example, interested in learning Unity, you can pay attention to the public number: poetic code, message to me, I teach you systematic learning.