首页 > 解决方案 > 如何在 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 去左边时需要再次处于相同位置...谢谢

标签: c#unity3dgame-development

解决方案


试试 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


推荐阅读