【3min 简单示例】Unity 通过 C# 脚本移动游戏物体

以匀速移动一个立方体对象为例,展示具体位移编码操作

欢迎关注 、订阅专栏 【unity 新手教程】谢谢你的支持!💜💜

Unity 通过 C# 脚本移动游戏物体

  1. 新建脚本文件 xxx.cs:Project 窗口右键 - Creat - C# Scripts - 右键创建好的 C# 文件 - Rename
    在这里插入图片描述

  2. 双击 C# 文件在 VS 中打开,初始内容如下:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class xxx : MonoBehaviour  
    {
        // Start is called before the first frame update
        void Start()
        {
        }
    
        // Update is called once per frame
        void Update()
        {
        }
    }
    
  3. 修改代码,保存(保存之后会自动编译,不用手动管)

    // 匀速移动核心代码
    float speed = 1.0f
    this.transform.Translate(speed * Time.deltaTime, 0, 0);
    

    //匀速移动完整代码
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class xxx : MonoBehaviour  // 类名与文件名一致,需要修改的话:右键类名 - 重命名 - 即可同步修改
    {
    	// 成员属性
    	
        // Start is called before the first frame update
        void Start()
        {
            // Debug.Log("** xxx ... ");  // 运行后,会在控制台窗口显示
            
    		GameObject obj = this.gameObject;  // 获取当前所挂载的游戏物体
    		
            // Debug.Log("** NAME: " + obj.name);  // 打印游戏物体名称
    		
            Vector3 pos = obj.transform.LocalPosition;  // 如果需要全局坐标系下的位置,则用 .position
            Debug.Log("** POS: " + pos);  // 打印位置,LocalPosition 与 inspector 中显示一致
    
    		// #### 场景 1. 游戏开始前移动物体到指定初始位置
    		// obj.transform.localPosition = new Vector3(1.0f, 1.1f, 1.2f);  // 移动到指定位置 (1.0f, 1.1f, 1.2f)
    		
        }
    
        // Update is called once per frame (每帧都更新,帧率不固定)
        void Update()
        {
            Debug.Log("Time delta" + Time.deltaTime);  // 打印两帧时间间隔
    
    		// #### 场景 2. 非严格匀速移动:每帧移动固定距离,如 0.01f
    		// Vector3 pos = this.transform.localPosition;
    		// pos.x += 0.01f;
    		// this.transform.localPosition = pos;
    
    		// #### 场景 3 【更新 localPosition 写法】. 严格匀速移动,速度设定为 speed 
    		//Vector3 pos = this.transform.localPosition;
    		//float speed = 1.0f;
    		//pos.x += speed*Time.deltaTime;
    		//this.transform.localPosition = pos;	
    		
    		// #### 场景 3 【简单写法:利用坐标增量更新】. 严格匀速移动,速度设定为 speed 
    		float speed = 1.0f
    		this.transform.Translate(speed * Time.deltaTime, 0, 0);	  // 默认为	space.Self -- 物体自身坐标系
    		// this.transform.Translate(speed * Time.deltaTime, 0, 0,Space.World);  // Global -- 世界坐标系 
        }
    }
    
  4. 挂载:直接拖动到目标物体的 Inspector 窗口中

  5. 运行:运行游戏,脚本会自动被加载、运行


欢迎关注 、订阅专栏 【unity 新手教程】谢谢你的支持!💜💜

<think>我们正在Unity中实现一个无人机降落的控制脚本。用户希望按下键盘的S键时,无人机能够执行降落动作。这里我们假设无人机已经有一个控制脚本,我们只需要添加降落功能。通常,降落可以通过减小高度(y坐标)来实现。注意:无人机的控制可能已经有一个飞行控制系统,但我们这里简化处理,直接控制高度。步骤:1.在Update函数中检测按键输入。2.当按下S键时,降低无人机的高度。然而,直接突然降低高度可能不够平滑,因此我们可以使用一个逐渐降低的速度。假设:-我们有一个变量`landingSpeed`表示降落速度(单位/秒)。-无人机的Transform组件用于调整位置。代码结构:我们将创建一个C#脚本,挂载到无人机物体上。注意:我们需要考虑重力或其他因素吗?这里简单处理,仅通过键盘控制。但更合理的做法是:在飞行控制中,通常有垂直速度控制。我们假设当按下S键时,无人机的垂直速度向下增加,直到一个最大值,然后持续下降。但为了简单,我们可以每帧减少一个固定值。我们也可以使用CharacterController或Rigidbody来控制,但这里用户没有指定,我们直接操作Transform。考虑到可能有多个控制(比如上升和下降),我们也可以同时支持W键上升,S键下降。脚本名:DroneController代码如下:</think> 以下是一个在Unity中控制无人机降落的C#脚本示例,当按下键盘S键时,无人机会平滑下降: ```csharp using UnityEngine; public class DroneController : MonoBehaviour { [Header("降落参数")] [Tooltip("下降速度 (米/秒)")] public float descentSpeed = 2.0f; // $v_d = 2\text{m/s}$ [Tooltip("最低高度限制 (米)")] public float minHeight = 1.0f; // $h_{\min} = 1\text{m}$ private Rigidbody rb; private bool isLanding = false; void Start() { // 获取无人机的刚体组件 rb = GetComponent<Rigidbody>(); if(rb == null) { Debug.LogError("未找到Rigidbody组件,请为无人机添加刚体"); } } void Update() { // 检测S键按下(持续检测) if(Input.GetKey(KeyCode.S)) { StartLanding(); } else if(Input.GetKeyUp(KeyCode.S)) { StopLanding(); } } void FixedUpdate() { // 物理更新中执行降落 if(isLanding) { ApplyLandingForce(); } } void StartLanding() { isLanding = true; Debug.Log("降落指令已接收"); } void StopLanding() { isLanding = false; Debug.Log("降落停止"); } void ApplyLandingForce() { // 检查是否已达到最低高度 if(transform.position.y > minHeight) { // 计算下降力(使用负值使物体下降) Vector3 descentForce = Vector3.down * descentSpeed; // 应用力(使用VelocityChange使运动更直接) rb.AddForce(descentForce, ForceMode.VelocityChange); // 可选:添加着陆指示灯效果 GetComponent<Renderer>().material.color = Color.red; } else { Debug.Log("已达到最低高度,停止降落"); isLanding = false; // 恢复原始颜色 GetComponent<Renderer>().material.color = Color.white; } } } ``` ### 使用说明: 1. **组件要求**: - 将脚本附加到无人机GameObject - 无人机必须包含`Rigidbody`组件 - 建议勾选Rigidbody的`Use Gravity`属性 2. **参数调整**: - `descentSpeed`:控制下降速度(建议2-5m/s) - `minHeight`:设置无人机可下降的最低高度 3. **控制逻辑**: - 按住 **S键**:无人机持续下降 - 松开 **S键**:停止降落 - 到达最低高度时自动停止 4. **高级功能扩展**: ```csharp // 添加缓动效果(在ApplyLandingForce方法中替换AddForce调用) float smoothDescent = Mathf.Lerp(rb.velocity.y, -descentSpeed, Time.fixedDeltaTime * 5f); rb.velocity = new Vector3(rb.velocity.x, smoothDescent, rb.velocity.z); ``` ### 注意事项: 1. 使用`FixedUpdate`保证物理模拟稳定性[^1] 2. 通过`ForceMode.VelocityChange`实现直接速度控制 3. 高度检测防止穿透地面 4. 添加了视觉反馈(材质颜色变化) > **调试提示**:可在Scene视图中添加Gizmos显示降落区域: > ```csharp > void OnDrawGizmosSelected() { > Gizmos.color = Color.yellow; > Gizmos.DrawWireCube(transform.position + Vector3.up * minHeight/2, > new Vector3(2, minHeight, 2)); > } > ``` [^1]: Unity物理系统在FixedUpdate中更新,频率默认为0.02秒(50Hz)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值