如何实现点击上箭头时transform.position.z增加5?代码为何异常?
问题分析与解决方案
核心问题
你代码里的关键错误是把单次触发的按键事件和基于时间的持续移动逻辑混在了一起:
Input.GetKeyDown(KeyCode.UpArrow)只在按下按键的那一帧返回true,属于单次触发的瞬时动作;Time.deltaTime是当前帧与上一帧的时间间隔,作用是让持续动作(比如按住按键移动)保持帧率无关的稳定速度,但用在单次触发场景里,只会让每次加上一个和当前帧时长挂钩的小数值,这就是你看到“随机多位小数”的原因。
另外你想要的是每次点击增加5,但代码里写的是1 * Time.deltaTime * 60,就算逻辑正确,数值也达不到预期。
修正后的代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveCamera : MonoBehaviour { void Start() {} void Update() { if(Input.GetKeyDown(KeyCode.UpArrow)) { // 单次按下直接给z轴加5,无需Time.deltaTime transform.position += new Vector3(0, 0, 5); } } }
补充说明
如果你的需求是按住上箭头时持续移动(保持帧率无关的稳定速度),那应该用Input.GetKey(按住期间每帧返回true),同时保留Time.deltaTime,示例代码如下:
if(Input.GetKey(KeyCode.UpArrow)) { // 每秒移动60单位的稳定速度 transform.position += new Vector3(0, 0, 1) * Time.deltaTime * 60; }
内容的提问来源于stack exchange,提问作者SomehowStillAlive
相关产品推荐
相关产品推荐

