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);
        }
    }
}
相关推荐
★YUI★4 小时前
学习游戏制作记录(玩家掉落系统,删除物品功能和独特物品)8.17
java·学习·游戏·unity·c#
SmalBox4 小时前
【渲染流水线】[光栅阶段]-[光栅插值]以UnityURP为例
unity·渲染
谷宇.5 小时前
【Unity3D实例-功能-拔枪】角色拔枪(二)分割上身和下身
游戏·unity·c#·游戏程序·unity3d·游戏开发·游戏编程
NRatel1 天前
亚马逊S3的使用简记(游戏资源发布更新)
游戏·unity·amazon s3
SmalBox1 天前
【渲染流水线】[几何阶段]-[屏幕映射]以UnityURP为例
unity·渲染
SmalBox2 天前
【渲染流水线】[几何阶段]-[归一化NDC]以UnityURP为例
unity·渲染
SmalBox3 天前
【渲染流水线】[几何阶段]-[图元装配]以UnityURP为例
unity·渲染
霜绛3 天前
Unity:GUI笔记(一)——文本、按钮、多选框和单选框、输入框和拖动条、图片绘制和框绘制
笔记·学习·unity·游戏引擎
谷宇.4 天前
【Unity3D实例-功能-移动】角色行走和奔跑的相互切换
游戏·unity·c#·unity3d·游戏开发·游戏编程
17岁的勇气4 天前
Unity Shader unity文档学习笔记(十九):粘土效果,任意网格转化成一个球(顶点动画,曲面着色器)
笔记·学习·unity·图形渲染·顶点着色器·曲面着色器