今天写一个unity的小教程,就以刚刚写的第一人称的射击小游戏作为案例。
先上效果图:\
\
首先游戏物品也没有多少东西,就是地板,平行光,主摄像机。然后我们需要做一个子弹,这个子弹里面添加刚体。然后把它作为预设体保存。
生成fire.cs文件。
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);
}
}
}
这份代码直接挂在摄像机上面。newObject就是放入刚刚保存的预设体子弹就行了。
代码解析:
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;
float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
这里是管摄像头,也就是第一人称上下左右移动的。
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);
}
剩下这部分代码也就是管键盘事件。键盘按键输入,然后控制摄像机旋转,达到镜头左右上下转动的效果。
这个是一个比较基础简单的游戏实例,有兴趣学unity的话,可以关注公众号:诗一样的代码,留言给我,我教你系统地学。