c# - 如何将 FixedUpdate 变量更改与用户输入对齐
问题描述
我正在创建一个小的无尽跑步者,玩家必须在屏幕上上下滑动才能移动鱼。想象一下 Subway Surfers,您可以在其中顺畅地行驶,而不是仅仅向左或向右跳跃一英尺。无论如何,我试图让鱼在玩家手指的大致方向上旋转,并在玩家放开屏幕时逐渐旋转回来。程序运行得几乎很顺利——除了鱼不断地旋转回到默认位置的事实,所以它看起来确实有问题。
这个脚本的工作方式是它接受两个 Vector2 变量——鱼的当前位置和以前的位置。然后它减去这些以获得表示自上一帧以来位置变化的 Vector2。然后我将其输入 Mathf.Atan 以获取该运动的方向。最后,我将鱼旋转这个新的量 - 减去它当前的旋转 - 让它朝着正确的方向前进。我将在下面显示代码。在调查了为什么这会导致鱼在几帧中不断地旋转回 0 度,一遍又一遍,我了解到 Unity 认为 y 位置的变化是每隔一帧切换到零的东西。我所有的代码都在 FixedUpdate 上运行,我没有在任何地方使用 Update,所以我不知道为什么它会如此不规律地切换。如果在更新期间测量用户触摸输入,这可能是问题的根源,但如果我能找到解决方案,那就太好了。我只是有点困惑,如果有人能尽快为我解决这个问题,我会很高兴。
现在这是我的“RotateByTouch”类代码:
C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateByTouch : MonoBehaviour {
public TrackObjectMotion trackObjectMotion;
public GameObject thisObject;
public float rotationValue;
void FixedUpdate() {
rotationValue = Mathf.Atan(trackObjectMotion.DeltaY / trackObjectMotion.DeltaX) * Mathf.Rad2Deg;
thisObject.transform.Rotate(Vector3.forward, rotationValue - thisObject.transform.rotation.eulerAngles.z);
}
}
这是我的“TrackObjectMotion”类的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrackObjectMotion : MonoBehaviour {
public Vector3 CurrentPosition;
public Vector3 PreviousPosition;
public float DeltaX;
public float DeltaY;
// Update is called once per frame
void FixedUpdate() {
PreviousPosition = CurrentPosition;
CurrentPosition = this.gameObject.transform.position;
DeltaX = CurrentPosition.x - PreviousPosition.x;
DeltaY = CurrentPosition.y - PreviousPosition.y;
}
}
最后,这是我用于实际移动鱼的代码:
public void FixedUpdate() {
foreach(Touch touch in Input.touches) {
if(touch.Phase == TouchPhase.Moved) {
this.transform.Translate(0, touch.deltaPosition.y, 0);
}
}
}
最后一点只是省略了一些关于乘以常数以获得所需结果的信息,但这并不重要。
解决方案
推荐阅读
- powershell - 将带有撇号的文件名的批处理文件传递给powershell命令
- angular - Angular 10 Formly + 材质垂直多选框
- laravel - 附加多态关系?
- javascript - jQuery / Javascript总和按预期计算
- javascript - 调用堆栈超出快速排序功能
- r - 通过使用 dplyr 添加前缀重命名除 id 列之外的所有列
- python - 在 Python 这样的编程语言和 Tensorflow 这样的平台中,“API”是什么意思?
- flutter - Flutter: chopper_generator >=3.0.4 与 moor_generator ^4.1.0 不兼容,如何解决?
- python - 写入同一视频后,视频的 NumPy 数组从原始数组发生变化
- android - 无法更改 Lifetime(time_to_live) firebase 推送通知