c# - 如何在 x 轴上平滑移动对象?
问题描述
我想问我如何才能将x轴上的对象平滑地左右移动?我只想在 X 轴上精确移动,其中 z 和 y 轴将与移动前保持相同。我尝试了代码:
rb.Transform.Translate(Vector3.right * Time.deltatime * 130);
但这会传送我想要快速移动的玩家我想要多少。我只想在 x 轴上添加,例如,如果对象打开
0->X
0->Y
0->Z
我想向右移动,然后x轴需要= 4,如果对象向右移动并且它的坐标(4,0,0)我想回到(0,0,0),我想向左移动) 当按键离开时。当我想要多一个字段时,坐标需要是(-4,0,0)我希望有人能得到我想要实现的目标。
编辑:
蓝星是位置上的玩家,我只想在 YZ 保持不变的 x 轴上平滑地向右和向左移动,图片上是我想要移动的方式,我只想平滑移动而不是瞬移
蓝色是玩家所在的位置,黄色和绿色的星星是玩家需要去的地方 何时去右边 OFC 去左边时需要再次处于相同位置...谢谢
解决方案
试试 Vector3.Lerp
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
// Transforms to act as start and end markers for the journey.
public Transform startMarker;
public Transform endMarker;
// Movement speed in units/sec.
public float speed = 1.0F;
// Time when the movement started.
private float startTime;
// Total distance between the markers.
private float journeyLength;
void Start()
{
// Keep a note of the time the movement started.
startTime = Time.time;
// Calculate the journey length.
journeyLength = Vector3.Distance(startMarker.position, endMarker.position);
}
// Follows the target position like with a spring
void Update()
{
// Distance moved = time * speed.
float distCovered = (Time.time - startTime) * speed;
// Fraction of journey completed = current distance divided by total distance.
float fracJourney = distCovered / journeyLength;
// Set our position as a fraction of the distance between the markers.
transform.position = Vector3.Lerp(startMarker.position, endMarker.position, fracJourney);
}
}
来源:https ://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
推荐阅读
- c++ - 如何创建和调用与其他函数同名的函数?
- node.js - 使用 SSL 和 Cloudflare 的 NodeJs 应用程序变慢
- excel - 尝试使用 if 语句来获取单元格中的 exordium right bij 文本
- java - 如何使用firebase将OTP发送到手机号SpringBoot?
- ubuntu - 与原生 Windows NPM/Yarn 处理相比,为什么 WSL 非常慢?
- javascript - 如何根据其值突出显示表格中的单元格
- python - 未检测到安装在同一文件夹中的依赖项?
- javafx - JavaFX 中的按键侦听器在按下按钮时发生变化
- java - java.net.SocketException:将服务从 Java 8 升级到 Java 11 时管道损坏(写入失败)
- spring-boot - 在vaadin的每一页前制作过滤器的最佳方法是什么