Unity坦克实战

unity坦克实战(一)

制作一款完整的坦克对战游戏
素材百度网盘链接
提取码:g82d
1.1 导入坦克模型
1.1.1导入模型
先在Unity3D的project面板中创建一个文件夹将坦克模型资源以及贴图拖拽到里面,命名为Materials,里面放置模型及其所需的材质。
1.1.2调整大小
将模型拖到Hierarchy窗口一般来讲可根据新创建的立方体(默认长宽高为1米1米1米)来确定其大小,可以设置Scale Factor的值来调整。选中坦克模型在弹出的inspector面板中点击Model,即可调整模型大小,这里将Scale Factor的值设为0.005。
1.1.3 材质和贴图
在Materials文件中根据其贴图自行组装坦克,也可以尝试其他模型。
1.1.4 行走控制
Input.GetKey(“Horizontal”)为收获横轴轴向的方法,及按下“左”键时,该方法返回-1,按下“右”键时该方法返回1.
Input.GetAxis(“Vertical”)为获取纵轴轴向的方法,安“上”返回1,“下”返回-1。
Time.deltaTime:指的是两次执行Update的时间间隔。“距离=速度时间”,故坦克在每次Update中的移动距离为“距离=速度时间”。
速度方向:transform的right,up和forward分别代表物体自身坐标系x,y,z这3个轴的方向,其中forward代表Z轴,即坦克前进的方向。由于速度是矢量,因此“速度=transform.forward*speed"指的是坦克在前进的方向上,每秒移动的速度值speed指定的距离,

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tank : MonoBehaviour {

    public Transform turret;
    private float turretRotSpeed = 0.5f;

    private float turretRotTarget = 0;
    private float turretRollTarget = 0;
    public Transform gun;
    private float maxRoll = 10f;
    private float minRoll=-4f;
	void Start () {
	}	
	void Update () {
        float steer = 20;//steer为旋转速度
        float x = Input.GetAxis("Horizontal");
        transform.Rotate(0, x * steer * Time.deltaTime, 0);
        //前进后退,speed为移动速度
        float speed = 3f;
        float y = Input.GetAxis("Vertical");
        //s为移动距离
        Vector3 s = y * transform.forward * speed * Time.deltaTime;
        transform.transform.position += s;//
    }
}

运行游戏后便可以通过左右键控制坦克的方向,上下控制前进或后退了。
1.2 相机跟随
实现:1)相机跟随坦克移动。
2) 鼠标控制相机的角度。
3)鼠标滚轮调整相机与坦克的距离。
1.2.1 跟随算法
新建名为CameraFollow.cs的文件,代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour {
    public float distance = 15;//距离
    public float rot = 0;//横向角度
    private float roll = 30f * Mathf.PI * 2 / 360;//纵向角度
    private GameObject target;//目标物体
    void Start () {
		target=GameObject.Find("tank");//找到坦克
	}
     void LateUpdate()
    {
    //一些判断
        if (target == null)
            return;
        if (Camera.main == null)
            return;
      //目标的坐标
        Vector3 targetPos = target.transform.position;
        //用三角函数计算相机的位置
        Vector3 cameraPos;
        float d = distance * Mathf.Cos(roll);
        float height = distance * Mathf.Sin(roll);
        cameraPos.x = targetPos.x + d * Mathf.Cos(rot);
        cameraPos.z = targetPos.z + d * Mathf.Sin(rot);
        cameraPos.y = targetPos.y + height;
        Camera.main.transform.position = cameraPos;
        Camera.main.transform.LookAt(target.transform);
    }
}

由于Mathf.Sin和Mathf.Cos使用弧度作为单位,因此这里的角度都用弧度来表示。”弧度=角度2Π/360“可得,30fMathf.PI*2/360就是30度所对应的弧度值。

你可能感兴趣的:(Unity坦克实战)