Unity实现简易坦克移动打炮

功能 :坦克可以前后移动、左右旋转、打炮
动态演示效果

静态展示图片

核心代码
1、Bullet.cs挂载在Bullet预设体上

csharp 复制代码
using UnityEngine;

public class Bullet : MonoBehaviour
{
    // 移动方向
    private Vector3 moveDir;
    // 移动速度
    private float moveSpeed = 2;

    /// <summary>
    /// 设置子弹移动方向
    /// </summary>
    /// <param name="bulletMoveDir">子弹移动方向</param>
    public void setMoveDir(Vector3 bulletMoveDir)
    {
        moveDir = bulletMoveDir;
    }

    private void Awake()
    {
        // 设置子弹生成后3秒销毁
        Destroy(this.gameObject, 3);
    }

    // Update is called once per frame
    void Update()
    {
        // 更新子弹位置
        transform.position += moveDir * Time.deltaTime * moveSpeed;
    }
}

2、Tank.cs挂载在Tank空对象上

csharp 复制代码
using UnityEngine;

public class Tank : MonoBehaviour
{
    [Header("炮弹的预设体")]
    public GameObject bulletPrefab;
    // 移动速度
    private float moveSpeed = 1;
    // 旋转速度
    private float rotateSpeed = 30;
    // 开火点
    Transform firePoint;

    private void Awake()
    {
        // FirePos为空对象,提供子弹的发射位置信息
        firePoint = transform.Find("FirePos");
    }

    // Update is called once per frame
    void Update()
    {
        // 左右旋转
        float hValue = Input.GetAxis("Horizontal");
        transform.eulerAngles += transform.up * hValue * Time.deltaTime * rotateSpeed;
        
        // 前后移动
        float vValue = Input.GetAxis("Vertical");
        transform.position += transform.forward * vValue * Time.deltaTime * moveSpeed;
       
        // 开火
        if (Input.GetKeyDown(KeyCode.J))
        {
            // 在开火点生成子弹
            GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
            // 设置子弹的移动方向为坦克的前方(在Unity场景中调整FirePos的transform与坦克的transform一致)
            bullet.GetComponent<Bullet>().setMoveDir(transform.forward);
        }
    }
}
相关推荐
DaLiangChen3 小时前
Unity 实用工具:动态绘制物体边界包围盒(支持屏幕固定线宽)
unity·游戏引擎
张老师带你学3 小时前
Unity 食物 农产品相关
科技·游戏·unity·游戏引擎·模型
mxwin3 小时前
Unity Custom Interpolators与半透明阴影的原理与实战
unity·游戏引擎·shader
晴夏。4 小时前
UE5第三人称模板实现及相关引擎源码分析
unity·ue5·游戏引擎·ue
HAPPY酷4 小时前
解决 Unreal Engine 编译报错 MSB4018:三个核心排查方向
游戏引擎·虚幻
晴夏。8 小时前
UE原生MovementBase实现分析
游戏引擎·ue·3c
天人合一peng9 小时前
Unity工程发布hololens需安装, MRTK安装
unity·游戏引擎·hololens
weixin_409383129 小时前
godot 调用class方法得用实例 不能用脚本引用
游戏引擎·godot
风酥糖10 小时前
Godot游戏练习01-第32节-国际化
游戏·游戏引擎·godot
魔士于安10 小时前
Unity类似博物馆场景
前端·unity·游戏引擎·贴图·模型