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);
        }
    }
}
相关推荐
KhalilRuan12 小时前
Unity Demo-3DFarm详解-其二
unity·游戏引擎
死也不注释17 小时前
【unity编辑器开发与拓展EditorGUILayoyt和GUILayoyt】
unity·编辑器·游戏引擎
Zillionnn2 天前
Unreal Engine 自动设置图像
游戏引擎·虚幻
2 天前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
马特说2 天前
Unity VR手术模拟系统架构分析与数据流设计
unity·系统架构·vr
心前阳光3 天前
Unity WebGL文本输入
unity·游戏引擎·webgl
天涯过客TYGK3 天前
unity A星寻路
unity·游戏引擎
KhalilRuan3 天前
Unity Demo——3D平台跳跃游戏笔记
笔记·游戏·unity·游戏引擎
AA陈超4 天前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻
ttod_qzstudio4 天前
Unity中使用EzySlice实现模型切割与UV控制完全指南
unity