1.人物移动:
public class RigibodywithSphere : MonoBehaviour {
Rigidbody rd;
public float powerN = 10.0f;
public int iCount = 5;
// Use this for initialization
void Start () {
rd = this.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
float inputHValue = Input.GetAxis("Horizontal");
float inputVValue = Input.GetAxis("Vertical");
rd.AddForce(Vector3.left*powerN*inputHValue,ForceMode.Impulse);
rd.AddForce(Vector3.forward * powerN * inputVValue, ForceMode.Impulse);
}
2.相机跟随:
public class camerflower : MonoBehaviour {
public Transform playerFlower;
Vector3 offset;
// Use this for initialization
void Start () {
//获取相机与目标的距离
offset = transform.position - playerFlower.position;
}
// Update is called once per frame
void Update () {
//更新相机方向,保持距离
transform.position = offset + playerFlower.position;
}
3.UI设计
public class UI : MonoBehaviour
{
public Text score;
public GameObject gameover;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
score.text = "Score:" + GM.score;
if (!GM.isActive)
{
gameover.SetActive(true);
}
}
}
4.克隆及随机生成
public class spawn : MonoBehaviour {
//需要克隆的物体
public GameObject colum;
//克隆时间
public float colddown = 2.0f;
float nextSpawn;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(GM.isActive)
{
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + colddown;
Vector3 spawnP = transform.position;
spawnP.y += Random.Range(-2.5f, 2f);
Instantiate(colum,spawnP,transform.rotation);
}
}注:随机生产与摧毁不可在同一代码中,不然将不能克隆物体
}
}
5.触发函数
要使用Trigger检测物体进入,则需要勾选Is Trigger选项
碰撞检测触发器Trigger 有别于碰撞检测器 Collision,其可以不受物理效果影响,一些可穿透区域的碰撞检测,可以使用Trigger来进行碰撞检测
常用方法如下:
OnTriggerEnter 进入时
OnTriggerExit 离开时
OnTriggerStay 处于时
同上碰撞检测器 Collision 也有3个方法:
OnCollisionEnter
OnCollisionExit
OnCollisionStay
这里我们需要为跑道添加一个终点撞线的机制,所以使用可穿透的碰撞检测触发器Trigger
代码如下:
OnTriggerEnter传入的参数必须为Collider,故能触发该函数的对象必须具有Collider组建。
这里我们用的是角色控制器Character Controller 自带了Collider组建
此时每当有角色撞线时即会打印角色名及系统时间
6.子弹移动
//给子弹添加这个脚本,沿某个方向移动
GetComponent<Rigidbody>().velocity = transform.forward * speed;
//按下某个j键发射,gun是发射点,发射点跟人物移动就行
if (Input.GetKey(KeyCode.J) && Time.time > nextfire)
{
nextfire = Time.time + firerate;
Instantiate(bolt, gun.position, gun.rotation);
}
7.2D游戏场景切换
导入文件 using UnityEngine.SceneManagement
SceneManagement.LoadScene(“加场景名字”)
8.追踪目标人物