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);
        }
    }
}
相关推荐
绀目澄清4 分钟前
unity3d AI Navigation 中文文档
游戏·unity
绀目澄清2 小时前
Unity 的AI Navigation 系统详细总结
人工智能·unity·游戏引擎
绀目澄清3 小时前
Unity3D AI Navigation 详解:从基础概念到实战应用
unity·游戏引擎
weixin_409383124 小时前
cocos shader流光文字 不显示透明部分
游戏引擎·cocos2d
绀目澄清4 小时前
Unity3D AI导航系统完全指南:从核心概念到动画耦合
人工智能·unity
__water4 小时前
RHK《模型贴图自由更换位置》
unity·贴图·模型贴图·移动不丢失
JIes__5 小时前
Unity(二)——3D数学
unity·游戏引擎
淡海水5 小时前
【节点】[RandomRange节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·randomrange
weixin_4242946720 小时前
在Unity中,摄像机移动时出现“残影”或“闪烁”是常见问题,主要原因和处理方法。
unity·游戏引擎
孟无岐20 小时前
【Laya】Browser 使用说明
typescript·游戏引擎·游戏程序·laya