Unity官方案例之星际航行游戏(Space Shooter)学习总结

2022-08-04,,,

这几天我学习了《Unity官方案例精讲》的Space Shooter部分,这个案例作为刚刚学习Unity的入门还是不错的,这是整个案例的代码。
下面对我觉得比较常见的几个用法进行一下总结。

1、碰撞

发生碰撞的两个物体必须带有碰撞体 ,发生碰撞的两个物体至少有一个带有刚体,发生碰撞的两个物体必须有相对运动。

Rigidbody(刚体):通过物理模拟控制对象的位置,使对象的运动受到 Unity 物理引擎的控制。添加方法:在Hierarchy视图中选中对象,在右侧Inspector视图中点击Add Component按钮,选择Physics–Rididbody。
在脚本中用 FixedUpdate 函数来施加力和更改 Rigidbody 设置,而不用 Update。下面是移动带有刚体的对象的FixedUpdate函数部分代码,使用脚本时要记得完成对象和脚本的绑定

void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");//得到水平方向输入
        float moveVertical = Input.GetAxis("Vertical");//得到垂直方向输入
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        Rigidbody rb=GetComponent<Rigidbody>();
        if(rb!=null)
        {
            rb.velocity = movement * speed;
        }
    }

Collider(碰撞体):在Inspector视图的Physics–Mesh Collider中添加,设置碰撞体为触发器时记得要勾选Convex和Is Trigger。

2、设置对象运动范围

可以通过在类前面设置Boundary类来实现。

[System.Serializable]//添加可序列化的属性后Boundary类才可以在Inspector视图中看到
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}
public class Sample : MonoBehaviour
{
	...
}

然后在FixedUpdate函数中使用Mathf.Clamp函数限定刚体活动范围,记得在Inspector视图中为Boundary的xMin等参数赋值

/*static float Clamp(float value,float min,float max)
如果value的值小于min,则返回min;如果value的值大于max,则返回max*/
 rb.position = new Vector3(Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 
 0.0f, 
 Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax));

3、标识游戏对象

在Unity中,可用Tag标签标识游戏对象,在Inspector视图中可指定游戏对象的Tag,GameObject类的FindWithTag方法可用来查询Tag为指定名称且处于活动状态的游戏对象。

4、重新加载场景

using UnityEngine.SceneManagement; //引用命名空间 SceneManager.LoadScene(SceneManager.GetActiveScene().name);

本文地址:https://blog.csdn.net/qq_41308365/article/details/107312737

《Unity官方案例之星际航行游戏(Space Shooter)学习总结.doc》

下载本文的Word格式文档,以方便收藏与打印。