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);
        }
    }
}
相关推荐
全栈陈序员1 小时前
用Rust和Bevy打造2D平台游戏原型
开发语言·rust·游戏引擎·游戏程序
鹿野素材屋3 小时前
Unity模型中人形角色的嘴巴一直开着怎么办
unity
世洋Blog7 小时前
Unity面经-List底层原理、如何基于数组、如何扩容、List存储泛型、List有关在内存中的结构
unity·面试·c#·list
神秘的土鸡12 小时前
【CS创世SD NAND征文】为无人机打造可靠数据仓:工业级存储芯片CSNP32GCR01-AOW在飞控系统中的应用实践
嵌入式硬件·游戏引擎·无人机·cocos2d·雷龙
jtymyxmz1 天前
《Unity Shader》6.4.3 半兰伯特模型
unity·游戏引擎
AA陈超1 天前
ASC学习笔记0001:处理目标选择系统中当Actor拒绝目标确认时的调用
c++·笔记·学习·游戏·ue5·游戏引擎·虚幻
我的golang之路果然有问题1 天前
mac配置 unity+vscode的坑
开发语言·笔记·vscode·macos·unity·游戏引擎
于小汐在咯1 天前
【虚拟现实技术】在Unity里创建一个简单的AR项目
unity·ar·vr
HahaGiver6661 天前
Unity Shader Graph 3D 实例 - 一个简单的红外线扫描全身效果
3d·unity·游戏引擎
o***Z4481 天前
免费的WebAssembly游戏引擎,AssemblyScript
游戏引擎·wasm