untiy实现汽车漫游

实现效果

汽车漫游

1.创建汽车模型
导入汽车模型(FBX格式或其他3D格式),确保模型包含车轮、车身等部件。
为汽车添加碰撞体(如 Box Collider 或 Mesh Collider),避免穿透场景物体。
添加 Rigidbody 组件,启用重力并调整质量(Mass)以模拟物理效果。
在这里插入图片描述
2.编写汽车控制脚本

using UnityEngine;
using UnityEngine.UI; // 引入UI命名空间

public class CarController : MonoBehaviour
{
    public float maxSpeed = 20f;        // 最大速度
    public float acceleration = 5f;     // 加速度
    public float turnSpeed = 10f;       // 转向速度
    public bool isRoamingEnabled = true; // 漫游开关状态
    public Button roamToggleButton;     // 绑定的UI按钮
    public Text buttonText;             // 按钮上的文字组件

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();

        // 绑定按钮点击事件
        if (roamToggleButton != null)
        {
            roamToggleButton.onClick.AddListener(ToggleRoaming);
            UpdateButtonText(); // 初始化按钮文字
        }
    }

    void FixedUpdate()
    {
        if (isRoamingEnabled)
        {
            // 获取输入(仅在漫游启用时响应)
            float moveInput = Input.GetAxis("Vertical");    // W/S 或 上下箭头
            float turnInput = Input.GetAxis("Horizontal");  // A/D 或 左右箭头

            // 加速/减速
            Vector3 force = -transform.forward * moveInput * acceleration;
            rb.AddForce(force, ForceMode.Acceleration);

            // 限制最大速度
            if (rb.velocity.magnitude > maxSpeed)
                rb.velocity = rb.velocity.normalized * maxSpeed;

            // 转向
            float turn = turnInput * turnSpeed * Time.fixedDeltaTime;
            Quaternion turnRotation = Quaternion.Euler(0, turn, 0);
            rb.MoveRotation(rb.rotation * turnRotation);
        }
        else
        {
            // 漫游禁用时自动减速
            rb.velocity = Vector3.Lerp(rb.velocity, Vector3.zero, Time.fixedDeltaTime * 2f);
            rb.angularVelocity = Vector3.Lerp(rb.angularVelocity, Vector3.zero, Time.fixedDeltaTime * 2f);
        }
    }

    // 切换漫游开关状态
    private void ToggleRoaming()
    {
        isRoamingEnabled = !isRoamingEnabled;
        UpdateButtonText();
    }

    // 更新按钮文字显示
    private void UpdateButtonText()
    {
        if (buttonText != null)
            buttonText.text = isRoamingEnabled ? "停止漫游" : "开始漫游";
    }
}
  1. ​​配置输入
    打开 Edit > Project Settings > Input Manager,确保 Vertical 和 Horizontal 轴已正确绑定到键盘输入。
    4.摄像机跟随​
    ​​添加跟随脚本​
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCamera : MonoBehaviour
{
    public Transform target;
    public Vector3 offset = new Vector3(-60, 20, 0);
    public float smoothTime = 0.3f;
    public float rotationSmoothSpeed = 5f;  // 旋转平滑系数
    private Vector3 _velocity = Vector3.zero;

    void LateUpdate()
    {
        Vector3 desiredPosition = target.position + offset;
        transform.position = Vector3.SmoothDamp(
            transform.position,
            desiredPosition,
            ref _velocity,
            smoothTime
        );

        // 平滑旋转
        Quaternion targetRotation = Quaternion.LookRotation(target.position - transform.position);
        transform.rotation = Quaternion.Slerp(
            transform.rotation,
            targetRotation,
            rotationSmoothSpeed * Time.deltaTime
        );
    }
}

​​步骤 1:创建 UI 按钮​​
在 Hierarchy 面板右键 > ​​UI > Button​​,创建一个按钮。
调整按钮位置和文字:
选中按钮下的 Text 子对象,修改文字为 开始漫游。
在 Inspector 中调整按钮的 RectTransform 和颜色样式。
​​步骤 2:修改汽车控制脚本​​
在原有代码中添加 ​​漫游状态开关​​ 和 ​​按钮点击事件响应逻辑​​:

using UnityEngine;
using UnityEngine.UI; // 引入UI命名空间

public class CarController : MonoBehaviour
{
    public float maxSpeed = 20f;        // 最大速度
    public float acceleration = 5f;     // 加速度
    public float turnSpeed = 10f;       // 转向速度
    public bool isRoamingEnabled = true; // 漫游开关状态
    public Button roamToggleButton;     // 绑定的UI按钮
    public Text buttonText;             // 按钮上的文字组件

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        
        // 绑定按钮点击事件
        if (roamToggleButton != null)
        {
            roamToggleButton.onClick.AddListener(ToggleRoaming);
            UpdateButtonText(); // 初始化按钮文字
        }
    }

    void FixedUpdate()
    {
        if (isRoamingEnabled)
        {
            // 获取输入(仅在漫游启用时响应)
            float moveInput = Input.GetAxis("Vertical");    // W/S 或 上下箭头
            float turnInput = Input.GetAxis("Horizontal");  // A/D 或 左右箭头

            // 加速/减速
            Vector3 force = -transform.forward * moveInput * acceleration;
            rb.AddForce(force, ForceMode.Acceleration);

            // 限制最大速度
            if (rb.velocity.magnitude > maxSpeed)
                rb.velocity = rb.velocity.normalized * maxSpeed;

            // 转向
            float turn = turnInput * turnSpeed * Time.fixedDeltaTime;
            Quaternion turnRotation = Quaternion.Euler(0, turn, 0);
            rb.MoveRotation(rb.rotation * turnRotation);
        }
        else
        {
            // 漫游禁用时自动减速
            rb.velocity = Vector3.Lerp(rb.velocity, Vector3.zero, Time.fixedDeltaTime * 2f);
            rb.angularVelocity = Vector3.Lerp(rb.angularVelocity, Vector3.zero, Time.fixedDeltaTime * 2f);
        }
    }

    // 切换漫游开关状态
    private void ToggleRoaming()
    {
        isRoamingEnabled = !isRoamingEnabled;
        UpdateButtonText();
    }

    // 更新按钮文字显示
    private void UpdateButtonText()
    {
        if (buttonText != null)
            buttonText.text = isRoamingEnabled ? "停止漫游" : "开始漫游";
    }
}

步骤 3:绑定 UI 组件​​
选中汽车对象,找到 CarController 脚本组件。
将 Hierarchy 中的按钮拖拽到 Toggle Roam Button 字段。
展开按钮对象,将其子对象 Text 拖拽到 Button Text 字段。

### 如何在 Unity实现编辑器扩展并创建自定义编辑器工具 #### 定义自定义编辑窗口 为了创建一个新的编辑器窗口,需要定义一个继承自 `EditorWindow` 的类。此类允许开发者向 Unity 编辑器添加新的功能面板。 ```csharp using UnityEngine; using UnityEditor; public class CustomMenuEditor : EditorWindow { [MenuItem("Tools/Custom Menu")] static void ShowWindow() { GetWindow<CustomMenuEditor>("Custom Menu"); } void OnGUI() { GUILayout.Label("This is a custom editor window", EditorStyles.boldLabel); } } ``` 这段代码展示了如何通过菜单项打开一个名为 "Custom Menu" 的新窗口[^1]。 #### 扩展 Unity 工具栏 对于希望进一步定制工作流程的情况,可以通过第三方库如 **UnityToolbarExtender** 来增强默认的工具栏行为。此插件使得向现有工具条添加按钮变得简单快捷[^2]。 安装该包之后,在项目的任意脚本文件夹内新建 C# 文件,并编写如下所示的内容: ```csharp using UnityEngine; using UnityEditor; using Toolbar = Unity.Toolbar.Extender.Toolbar; [InitializeOnLoad] public class ToolBarExtension { static ToolBarExtension() { Toolbar.AddLeftElement(new GUIContent("NewButton"), () => Debug.Log("Clicked")); } } ``` 上述例子会在左侧位置增加一个标签为 “NewButton” 的按钮;点击它会打印一条消息到控制台。 #### 学习资源推荐 了解这些基础知识只是第一步,更全面的学习可以从官方文档以及社区分享的文章入手。一篇优秀的入门指南能够帮助理解更多关于编辑器拓展的核心概念和技术细节[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未央区邓紫棋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值