今天开始写一些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);
}
剩下这部分代码也就是管键盘事件。键盘按键输入,然后控制摄像机旋转,达到镜头左右上下转动的效果。
我们知道微软将会在今年给Windows10更换全新设计的UI,让Windows10的界面更加整...
git工作区,暂存区,版本库之间的关系: 我们建立的项目文件夹就是工作区,在初...
一、简介 本设计为硬币图像识别统计装置通过数码相机获取平铺无重叠堆积的硬币的...
本文实例讲述了jsp中page指令用法。分享给大家供大家参考。具体如下: 一、JSP ...
大家好,今天我们来简单的聊一聊缓存问题。什么是缓存呢?它在系统设计中是在一个...
今日国内领先的智能数据服务运营商觉非科技完成近亿元A轮融资。本轮融资由和高资...
一、MVC MVC模式的意思是,软件可以分成三个部分。 视图(View):用户界面。 控...
首先给扑克牌中每张牌设定一个编号,下面算法实现的编号规则如下: u 红桃按照从...
从功能测试、性能测试、界面测试、安全性测试、易用性、兼容性测试、震动测试七...
前言 关于Window,你了解多少呢?看看下面这些问题你都能答上来吗。 如果你遇到这...